ProtoBufHelper.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. //----------------------------------------------------------------
  7. //Module Name: $safeprojectname$
  8. //Purpose:
  9. //CopyRight: Muchinfo
  10. //History:
  11. //----------------------------------------------------------------
  12. //DateTime 2016/1/18 9:40:42
  13. //Author
  14. //Description Create
  15. //----------------------------------------------------------------
  16. using ProtoBuf;
  17. using tas;
  18. namespace Muchinfo.MTPClient.Adapter.Utilities
  19. {
  20. /// <summary>
  21. /// ProtoBuf序列化反序列化帮助类
  22. /// </summary>
  23. public class ProtoBufHelper
  24. {
  25. /// <summary>
  26. /// 登录保存的内容消息头
  27. /// </summary>
  28. public static MessageHead Head { get; set; }
  29. /// <summary>
  30. /// 实体使用ProtoBuf格式序列化
  31. /// </summary>
  32. /// <typeparam name="T">实体对象类型</typeparam>
  33. /// <param name="entity">实体对象</param>
  34. /// <param name="withoutHead">是否包括头</param>
  35. /// <returns>序列化后的字节</returns>
  36. public static byte[] EntitySerialize<T>(T entity, bool withoutHead = true)
  37. {
  38. if (withoutHead)
  39. {
  40. var type = entity.GetType();
  41. var property = type.GetProperty("Header");
  42. if (property != null && property.PropertyType.Equals(typeof(MessageHead)))
  43. {
  44. //todo:Head,要传交易端的时间
  45. if (Head != null)
  46. {
  47. var uuid = Guid.NewGuid();
  48. property.SetValue(entity, new MessageHead() { AccountID = Head.AccountID, UserID = Head.UserID, UUID = uuid.ToString() }, null);
  49. }
  50. }
  51. }
  52. using (System.IO.MemoryStream mStream = new MemoryStream())
  53. {
  54. Serializer.Serialize(mStream, entity);
  55. mStream.Position = 0;
  56. var buffer = new byte[mStream.Length];
  57. mStream.Read(buffer, 0, buffer.Length);
  58. mStream.Close();
  59. return buffer;
  60. }
  61. }
  62. /// <summary>
  63. /// 反序列化实体
  64. /// </summary>
  65. /// <typeparam name="T">实体对象类型</typeparam>
  66. /// <param name="buffer">The buffer.</param>
  67. /// <returns>``0.</returns>
  68. public static T EntityDeSerialize<T>(byte[] buffer)
  69. {
  70. using (var mStream = new MemoryStream(buffer))
  71. {
  72. mStream.Position = 0;
  73. var entity = Serializer.Deserialize<T>(mStream);
  74. mStream.Close();
  75. return entity;
  76. }
  77. }
  78. }
  79. }