ProtobufHelper.cs 1013 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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<T>(T message)
  9. {
  10. MemoryStream ms = new MemoryStream();
  11. Serializer.Serialize(ms, message);
  12. return ms.ToArray();
  13. }
  14. public static T FromBytes<T>(byte[] bytes)
  15. {
  16. MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length);
  17. T t = Serializer.Deserialize<T>(ms);
  18. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  19. if (iSupportInitialize == null)
  20. {
  21. return t;
  22. }
  23. iSupportInitialize.EndInit();
  24. return t;
  25. }
  26. public static T FromBytes<T>(byte[] bytes, int index, int length)
  27. {
  28. MemoryStream ms = new MemoryStream(bytes, index, length);
  29. T t = Serializer.Deserialize<T>(ms);
  30. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  31. if (iSupportInitialize == null)
  32. {
  33. return t;
  34. }
  35. iSupportInitialize.EndInit();
  36. return t;
  37. }
  38. }
  39. }