ProtobufHelper.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using ProtoBuf;
  5. namespace Base
  6. {
  7. public static class ProtobufHelper
  8. {
  9. public static byte[] ToBytes(object message)
  10. {
  11. using (MemoryStream ms = new MemoryStream())
  12. {
  13. Serializer.Serialize(ms, message);
  14. return ms.ToArray();
  15. }
  16. }
  17. public static T FromBytes<T>(byte[] bytes)
  18. {
  19. T t;
  20. using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
  21. {
  22. t = Serializer.Deserialize<T>(ms);
  23. }
  24. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  25. if (iSupportInitialize == null)
  26. {
  27. return t;
  28. }
  29. iSupportInitialize.EndInit();
  30. return t;
  31. }
  32. public static T FromBytes<T>(byte[] bytes, int index, int length)
  33. {
  34. T t;
  35. using (MemoryStream ms = new MemoryStream(bytes, index, length))
  36. {
  37. t = Serializer.Deserialize<T>(ms);
  38. }
  39. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  40. if (iSupportInitialize == null)
  41. {
  42. return t;
  43. }
  44. iSupportInitialize.EndInit();
  45. return t;
  46. }
  47. public static object FromBytes(Type type, byte[] bytes)
  48. {
  49. object t;
  50. using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
  51. {
  52. t = Serializer.NonGeneric.Deserialize(type, ms);
  53. }
  54. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  55. if (iSupportInitialize == null)
  56. {
  57. return t;
  58. }
  59. iSupportInitialize.EndInit();
  60. return t;
  61. }
  62. public static object FromBytes(Type type, byte[] bytes, int index, int length)
  63. {
  64. object t;
  65. using (MemoryStream ms = new MemoryStream(bytes, index, length))
  66. {
  67. t = Serializer.NonGeneric.Deserialize(type, ms);
  68. }
  69. ISupportInitialize iSupportInitialize = t as ISupportInitialize;
  70. if (iSupportInitialize == null)
  71. {
  72. return t;
  73. }
  74. iSupportInitialize.EndInit();
  75. return t;
  76. }
  77. }
  78. }