SerializeTool.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //************************************************************************
  2. // author: yuzhengyang
  3. // date: 2018.3.27 - 2018.6.3
  4. // desc: 工具描述
  5. // Copyright (c) yuzhengyang. All rights reserved.
  6. //************************************************************************
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.Serialization;
  12. using System.Runtime.Serialization.Formatters.Binary;
  13. using System.Text;
  14. namespace Azylee.Core.DataUtils.SerializeUtils
  15. {
  16. public static class SerializeTool
  17. {
  18. /// <summary>
  19. /// 序列化模型到 byte 数组 [Serializable]
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. /// <param name="model"></param>
  23. /// <returns></returns>
  24. public static byte[] Serialize<T>(T model)
  25. {
  26. if (model != null)
  27. {
  28. MemoryStream ms = null;
  29. try
  30. {
  31. ms = new MemoryStream(); //内存实例
  32. BinaryFormatter formatter = new BinaryFormatter(); //创建序列化的实例
  33. formatter.Serialize(ms, model);//序列化对象,写入ms流中
  34. byte[] bytes = ms.GetBuffer();
  35. return bytes;
  36. }
  37. catch { }
  38. finally
  39. {
  40. ms?.Close();
  41. }
  42. }
  43. return null;
  44. }
  45. public static T Deserialize<T>(byte[] bytes)
  46. {
  47. if (bytes != null)
  48. {
  49. MemoryStream ms = null;
  50. try
  51. {
  52. object obj = null;
  53. ms = new MemoryStream(bytes); //利用传来的byte[]创建一个内存流
  54. ms.Position = 0;
  55. BinaryFormatter formatter = new BinaryFormatter();
  56. obj = formatter.Deserialize(ms);//把内存流反序列成对象
  57. return (T)Convert.ChangeType(obj, typeof(T)); ;
  58. }
  59. catch { }
  60. finally
  61. {
  62. ms?.Close();
  63. }
  64. }
  65. return default(T);
  66. }
  67. }
  68. }