ProtobufHelper.cs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.ComponentModel;
  2. using System.IO;
  3. using ProtoBuf;
  4. namespace Common.Helper
  5. {
  6. public static class ProtobufHelper
  7. {
  8. public static byte[] ToBytes(object message)
  9. {
  10. using (MemoryStream ms = new MemoryStream())
  11. {
  12. Serializer.Serialize(ms, message);
  13. return ms.ToArray();
  14. }
  15. }
  16. public static T FromBytes<T>(byte[] bytes)
  17. {
  18. T t;
  19. using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
  20. {
  21. t = Serializer.Deserialize<T>(ms);
  22. }
  23. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  24. if (iSupportInitialize == null)
  25. {
  26. return t;
  27. }
  28. iSupportInitialize.EndInit();
  29. return t;
  30. }
  31. public static T FromBytes<T>(byte[] bytes, int index, int length)
  32. {
  33. T t;
  34. using (MemoryStream ms = new MemoryStream(bytes, index, length))
  35. {
  36. t = Serializer.Deserialize<T>(ms);
  37. }
  38. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  39. if (iSupportInitialize == null)
  40. {
  41. return t;
  42. }
  43. iSupportInitialize.EndInit();
  44. return t;
  45. }
  46. }
  47. }