using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; //---------------------------------------------------------------- //Module Name: $safeprojectname$ //Purpose: //CopyRight: Muchinfo //History: //---------------------------------------------------------------- //DateTime 2016/1/18 9:40:42 //Author //Description Create //---------------------------------------------------------------- using ProtoBuf; using tas; namespace Muchinfo.MTPClient.Adapter.Utilities { /// /// ProtoBuf序列化反序列化帮助类 /// public class ProtoBufHelper { /// /// 登录保存的内容消息头 /// public static MessageHead Head { get; set; } /// /// 实体使用ProtoBuf格式序列化 /// /// 实体对象类型 /// 实体对象 /// 是否包括头 /// 序列化后的字节 public static byte[] EntitySerialize(T entity, bool withoutHead = true) { if (withoutHead) { var type = entity.GetType(); var property = type.GetProperty("Header"); if (property != null && property.PropertyType.Equals(typeof(MessageHead))) { //todo:Head,要传交易端的时间 if (Head != null) { var uuid = Guid.NewGuid(); property.SetValue(entity, new MessageHead() { AccountID = Head.AccountID, UserID = Head.UserID, UUID = uuid.ToString() }, null); } } } using (System.IO.MemoryStream mStream = new MemoryStream()) { Serializer.Serialize(mStream, entity); mStream.Position = 0; var buffer = new byte[mStream.Length]; mStream.Read(buffer, 0, buffer.Length); mStream.Close(); return buffer; } } /// /// 反序列化实体 /// /// 实体对象类型 /// The buffer. /// ``0. public static T EntityDeSerialize(byte[] buffer) { using (var mStream = new MemoryStream(buffer)) { mStream.Position = 0; var entity = Serializer.Deserialize(mStream); mStream.Close(); return entity; } } } }