| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- 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
- {
- /// <summary>
- /// ProtoBuf序列化反序列化帮助类
- /// </summary>
- public class ProtoBufHelper
- {
- /// <summary>
- /// 登录保存的内容消息头
- /// </summary>
- public static MessageHead Head { get; set; }
- /// <summary>
- /// 实体使用ProtoBuf格式序列化
- /// </summary>
- /// <typeparam name="T">实体对象类型</typeparam>
- /// <param name="entity">实体对象</param>
- /// <param name="withoutHead">是否包括头</param>
- /// <returns>序列化后的字节</returns>
- public static byte[] EntitySerialize<T>(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;
- }
- }
- /// <summary>
- /// 反序列化实体
- /// </summary>
- /// <typeparam name="T">实体对象类型</typeparam>
- /// <param name="buffer">The buffer.</param>
- /// <returns>``0.</returns>
- public static T EntityDeSerialize<T>(byte[] buffer)
- {
- using (var mStream = new MemoryStream(buffer))
- {
- mStream.Position = 0;
- var entity = Serializer.Deserialize<T>(mStream);
- mStream.Close();
- return entity;
- }
- }
- }
- }
|