Unity使用protobuf-net进行二进制序列化与反序列化


Protobuf-net提供的一种易于使用的数据序列化方案,可序列化带有[ProtoContract]特性的类实例,并可支持Unity各个发布平台,且效率高、易用性强。

 1 public static class Serialization
 2 {
 3     public static byte[] Serialize<T>(T instance)
 4     {
 5         byte[] bytes;
 6         using (var ms = new MemoryStream())
 7         {
 8             Serializer.Serialize(ms, instance);
 9             bytes = new byte[ms.Position];
10             var fullBytes = ms.GetBuffer();
11             Array.Copy(fullBytes, bytes, bytes.Length);
12         }
13          return bytes;
14     }
15 
16     public static T Deserialize<T>(object obj)
17     {
18         byte[] bytes = (byte[]) obj;
19          using (var ms = new MemoryStream(bytes))
20         {
21              return Serializer.Deserialize<T>(ms);
22         }
23     }
24 }

以下为需要进行序列化的类定义示例。

 1 [ProtoContract]
 2 public class Example
 3 {
 4     // Protobuf 要求
 5     // 不带 [ProtoMember] C#特性的成员其值将不被序列化
 6     // IsRequired 是可选的
 7     // 如成员是自定义类对象,即该类是嵌套类,序号必须与类成员对象中的第一个成员序号相同
 8     // 若将所有自定义类成员在该类中展开,不能存在相同的序号
 9 
10     public int ClassName { get; set; }
11 
12     [ProtoMember(1, IsRequired = true)]
13     public Dictionary<int, int> Dictionary { get; set; }
14 
15     // 必须带有无参数默认构造函数
16     public Example()
17     {
18         Dictionary = new Dictionary<int, int>();
19     }
20 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM