C# 使用 protobuf ,序列化对象的方法 (用于快速存档)


打开 程序包管理器控制台 粘贴以下代码 后 按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();
发布了53 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/q158805972/article/details/100977788