SerializationUnit.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.Serialization.Formatters.Binary;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace ToolsClassLibrary.UDP
  9. {
  10. public class SerializationUnit
  11. {
  12. /// <summary>
  13. /// 把对象序列化为字节数组
  14. /// </summary>
  15. public static byte[] SerializeObject(object obj)
  16. {
  17. if (obj == null)
  18. return null;
  19. //内存实例
  20. MemoryStream ms = new MemoryStream();
  21. //创建序列化的实例
  22. BinaryFormatter formatter = new BinaryFormatter();
  23. formatter.Serialize(ms, obj);//序列化对象,写入ms流中
  24. ms.Position = 0;
  25. //byte[] bytes = new byte[ms.Length];//这个有错误
  26. byte[] bytes = ms.GetBuffer();
  27. ms.Read(bytes, 0, bytes.Length);
  28. ms.Close();
  29. return bytes;
  30. }
  31. /// <summary>
  32. /// 把字节数组反序列化成对象
  33. /// </summary>
  34. public static object DeserializeObject(byte[] bytes)
  35. {
  36. object obj = null;
  37. if (bytes == null)
  38. return obj;
  39. //利用传来的byte[]创建一个内存流
  40. MemoryStream ms = new MemoryStream(bytes);
  41. ms.Position = 0;
  42. BinaryFormatter formatter = new BinaryFormatter();
  43. obj = formatter.Deserialize(ms);//把内存流反序列成对象
  44. ms.Close();
  45. return obj;
  46. }
  47. /// <summary>
  48. /// 把字典序列化
  49. /// </summary>
  50. /// <param name="dic"></param>
  51. /// <returns></returns>
  52. public static byte[] SerializeDic(Dictionary<string, double> dic)
  53. {
  54. if (dic.Count == 0)
  55. return null;
  56. MemoryStream ms = new MemoryStream();
  57. BinaryFormatter formatter = new BinaryFormatter();
  58. formatter.Serialize(ms, dic);//把字典序列化成流
  59. byte[] bytes = new byte[ms.Length];//从流中读出byte[]
  60. ms.Read(bytes, 0, bytes.Length);
  61. return bytes;
  62. }
  63. /// <summary>
  64. /// 反序列化返回字典
  65. /// </summary>
  66. /// <param name="bytes"></param>
  67. /// <returns></returns>
  68. public static Dictionary<string, double> DeserializeDic(byte[] bytes)
  69. {
  70. Dictionary<string, double> dic = null;
  71. if (bytes == null)
  72. return dic;
  73. //利用传来的byte[]创建一个内存流
  74. MemoryStream ms = new MemoryStream(bytes);
  75. ms.Position = 0;
  76. BinaryFormatter formatter = new BinaryFormatter();
  77. //把流中转换为Dictionary
  78. dic = (Dictionary<string, double>)formatter.Deserialize(ms);
  79. return dic;
  80. }
  81. }
  82. }