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

下面小编就为大家带来一篇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对象二进制序列化存储(详解)的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程