1 using System.Runtime.Serialization.Formatters.Binary;
2 using System.IO;
3
4 //序列化是将对象状态转换为可保持或传输的格式的过程。
5 //与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。
6 public class Serialize
7 {
8 #region 二进制序列化
9 public static MemoryStream SerilaizeBinary(Object obj)//对象转内存流
10 {
11 MemoryStream memStream = new MemoryStream();
12 BinaryFormatter serilaze = new BinaryFormatter();
13 serilaze.Serialize(memStream,obj);
14 return memStream;
15 }
16
17 public static byte[] ObjectTobyte(object obj)//对象转字节数组
18 {
19 MemoryStream memStream = SerilaizeBinary(obj);
20 return memStream.ToArray();
21 }
22 #endregion
23
24 #region 二进制反序列化
25 public static object DeserilaizeBinary(MemoryStream memStream)
26 {
27 //内存流转对象
28 memStream.Position = 0;
29 BinaryFormatter Deserilaze = new BinaryFormatter();
30 object obj = Deserilaze.Deserialize(memStream);
31 memStream.Close();
32 return obj;
33 }
34
35 public static object ByteToObject(byte[]buffer)//字节数组转对象
36 {
37 MemoryStream memStream = new MemoryStream(buffer);
38 object obj = DeserilaizeBinary(memStream);
39 memStream.Close();
40 return obj;
41 }
42 #endregion
43 }