栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

protobuf对象二进制序列化存储(详解)

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

protobuf对象二进制序列化存储(详解)

首先下载protobuf库,可以用Nuget。

demo:

using System;

namespace Tools
{
  public class BufHelp
  {
    /// 
    /// 对象锁
    /// 
    private readonly static Object Locker = new Object();
    ///// 
    ///// 读写分离锁
    ///// 
    ///// aaaaa
    //private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();

    /// 
    /// 序列化-表字段业务信息
    /// 
    public static bool ProtoBufSerialize(T model, string filename) where T : class
    {
      try
      {
 string binpath = Config.KeyCenter.KeybaseDirectory + @"Config";

 if (!System.IO.Directory.Exists(binpath))
   System.IO.Directory.CreateDirectory(binpath);

 lock (Locker)
 {
   using (var file = System.IO.File.Create(binpath + filename))
   {
     ProtoBuf.Serializer.Serialize(file, model);
     return true;
   }
 }
      }
      catch
      {
 return false;
      }
    }

    public static T ProtoBufDeserialize(string filename) where T : class
    {
      var dbpath = Config.KeyCenter.KeybaseDirectory + @"Config" + filename;

      if (System.IO.File.Exists(dbpath))
      {
 lock (Locker)
 {
   using (var file = System.IO.File.OpenRead(dbpath))
   {
     var result = ProtoBuf.Serializer.Deserialize(file);
     return result;
   }
 }
      }

      return default(T);
    }
  }
}/// 
    /// 序列化
    /// 
    public static string Serialize(T t) where T : class
    {
      using (MemoryStream ms = new MemoryStream())
      {
 ProtoBuf.Serializer.Serialize(ms, t);
 return Encoding.UTF8.GetString(ms.ToArray());
      }
    }
    /// 
    /// 反序列化
    /// 
    public static T DeSerialize(string content) where T : class
    {
      using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
      {
 T t = ProtoBuf.Serializer.Deserialize(ms);
 return t;
      }
    }

以上这篇protobuf对象二进制序列化存储(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/123630.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号