SerializeHelper.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.Serialization.Formatters.Binary;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace OASystem.RedisRepository.CommonHelper
  8. {
  9. internal static class SerializeHelper
  10. {
  11. /// <summary>
  12. /// 字节数组序列化
  13. /// </summary>
  14. /// <param name="o"></param>
  15. /// <returns></returns>
  16. internal static byte[] Serialize(object o)
  17. {
  18. if (o == null)
  19. {
  20. return null;
  21. }
  22. BinaryFormatter binaryFormatter = new BinaryFormatter();
  23. using (MemoryStream memoryStream = new MemoryStream())
  24. {
  25. binaryFormatter.Serialize(memoryStream, o);
  26. byte[] objectDataAsStream = memoryStream.ToArray();
  27. return objectDataAsStream;
  28. }
  29. }
  30. /// <summary>
  31. /// 字节数组反序列化
  32. /// </summary>
  33. /// <typeparam name="T"></typeparam>
  34. /// <param name="stream"></param>
  35. /// <returns></returns>
  36. internal static T Deserialize<T>(byte[] stream)
  37. {
  38. if (stream == null)
  39. {
  40. return default(T);
  41. }
  42. BinaryFormatter binaryFormatter = new BinaryFormatter();
  43. using (MemoryStream memoryStream = new MemoryStream(stream))
  44. {
  45. T result = (T)binaryFormatter.Deserialize(memoryStream);
  46. return result;
  47. }
  48. }
  49. }
  50. }