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 }
