protobuf對象二進(jìn)制序列化存儲(詳解)
更新時間:2017年02月15日 10:49:59 投稿:jingxian
下面小編就為大家?guī)硪黄猵rotobuf對象二進(jìn)制序列化存儲(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
首先下載protobuf庫,可以用Nuget。
demo:
using System;
namespace Tools
{
public class BufHelp
{
/// <summary>
/// 對象鎖
/// </summary>
private readonly static Object Locker = new Object();
///// <summary>
///// 讀寫分離鎖
///// </summary>
///// <remarks>aaaaa</remarks>
//private static ReaderWriterLockSlim rwl = new ReaderWriterLockSlim();
/// <summary>
/// 序列化-表字段業(yè)務(wù)信息
/// </summary>
public static bool ProtoBufSerialize<T>(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<T>(file, model);
return true;
}
}
}
catch
{
return false;
}
}
public static T ProtoBufDeserialize<T>(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<T>(file);
return result;
}
}
}
return default(T);
}
}
}/// <summary>
/// 序列化
/// </summary>
public static string Serialize<T>(T t) where T : class
{
using (MemoryStream ms = new MemoryStream())
{
ProtoBuf.Serializer.Serialize<T>(ms, t);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// 反序列化
/// </summary>
public static T DeSerialize<T>(string content) where T : class
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
T t = ProtoBuf.Serializer.Deserialize<T>(ms);
return t;
}
}
以上這篇protobuf對象二進(jìn)制序列化存儲(詳解)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#中實現(xiàn)Fluent Interface的三種方法
這篇文章主要介紹了C#中實現(xiàn)Fluent Interface的三種方法,本文講解了Fluent Interface的簡單實現(xiàn)、使用裝飾器模式和擴展方法實現(xiàn)Fluent Interface等3種實現(xiàn)方法,需要的朋友可以參考下2015-03-03
C#使用后臺線程BackgroundWorker處理任務(wù)的總結(jié)
這篇文章主要介紹了C#使用后臺線程BackgroundWorker處理任務(wù)的總結(jié),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07

