打開 程序包管理器控制檯 粘貼以下代碼 後 按Enter鍵。
Install-Package protobuf-net
在文件里加入
using ProtoBuf;
如需序列化的類,
需要通過Attribute 修飾類名
[ProtoContract()]
class XX
{
[ProtoMember(1)]
public int hp = 64;
[ProtoMember(2)]
public int mp = 21;
[ProtoMember(3)]
public int ap = 34;
}
如何反序列化,序列化成文件,或內存流
MemoryStream memoryStream = new MemoryStream();
Serializer.Serialize(memoryStream, new yourObject());
以下是序列化成 Person.bin 文件, 注:擴展名可修改的。。
// ProtoBuf序列化
var file1 = System.IO.File.Create("Person.bin");
Serializer.Serialize(file1, 你的對象);
file1.Close();
file1.Dispose();
以下是從 Person.bin 文件反序列化出來 Man對象, 注:擴展名可修改的。。
Man binMan = null;
var file = System.IO.File.OpenRead("Person.bin");
//這樣就能 從文件反序列化出來 Man 對象了。 (用於快速存檔的!如遊戲開發)
binMan = Serializer.Deserialize<Man>(file);
file.Close();
file.Dispose();