前一篇文章我们看到使用Google.Protobuf有诸多不便(参考《如何在C#中使用Google.Protobuf工具》),这次我们来看看另一个工具的使用体验。
在类级别增加注解[ProtoContract],在字段级别增加注解[ProtoMember(orderxxx)]
[ProtoContract] public class ErrorLog { [ProtoMember(1)] public string LogID { get; set; } [ProtoMember(2)] public string Context { get; set; } [ProtoMember(3)] public string Stack { get; set; } }
当安装了protobuf-net.BuildTools工具后,还可以在开发时对目标类型(添加了[ProtoContract]注解)的定义进行检查,比如字段顺序重复、使用的字段类型不符合protobuf要求等。比如因疏忽设置了重复的字段顺序,提示效果如下:
public static byte[] Serialize(ErrorLog log) { using (MemoryStream memoryStream = new MemoryStream()) { ProtoBuf.Serializer.Serialize(memoryStream, log); return memoryStream.ToArray(); } }
public static ErrorLog DeSerialize(byte[] data) { using (MemoryStream ms = new MemoryStream(data)) { return ProtoBuf.Serializer.Deserialize<ErrorLog>(ms); } }