首先下载protobuf库,可以用Nuget。
demo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
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>
/// 序列化-表字段业务信息
/// </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对象二进制序列化存储(详解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。