序列化
前言
序列化分为序列化和反序列化。
作用是:可以持久化一个对象、可以方便安全地传输。
是保存状态的一种选择。
第一、创建一个对象,代码如下:(一定要加上[Serializable]这个特性)
1 [Serializable] 2 class Person 3 { 4 private string name; 5 6 public string Name 7 { 8 get { return name; } 9 set { name = value; } 10 } 11 private int age; 12 13 public int Age 14 { 15 get { return age; } 16 set { age = value; } 17 } 18 }
第二、把对象序列化到文件上,代码如下:
1 #region 序列化 2 Person p = new Person(); 3 p.Name = "zhanglong"; 4 p.Age = 34; 5 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 6 using (FileStream fs = new FileStream("sb.txt", FileMode.Create)) 7 { 8 bf.Serialize(fs, p); 9 } 10 #endregion 11 12 #region 反序列化 13 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter fd = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 14 using (FileStream fs = new FileStream("sb.txt", FileMode.Open)) 15 { 16 object obj = fd.Deserialize(fs); 17 Person p1 = obj as Person; 18 Console.WriteLine(p1.Name + ":" + p1.Age); 19 } 20 #endregion
第三、把对象序列化到内存上,代码如下:
1 /// <summary> 2 /// 序列化为二进制字节数组 3 /// </summary> 4 /// <param name="request">要序列化的对象</param> 5 /// <returns>字节数组</returns> 6 private static byte[] SerializeBinary(object request) 7 { 8 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer = 9 new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 10 System.IO.MemoryStream memStream = new System.IO.MemoryStream(); 11 serializer.Serialize(memStream, request); 12 return memStream.GetBuffer(); 13 } 14 15 /// <summary> 16 /// 从二进制数组反序列化得到对象 17 /// </summary> 18 /// <param name="buf">字节数组</param> 19 /// <returns>得到的对象</returns> 20 private static object DeserializeBinary(byte[] buf) 21 { 22 System.IO.MemoryStream memStream = new MemoryStream(buf); 23 memStream.Position = 0; 24 System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer = 25 new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); 26 object newobj = deserializer.Deserialize(memStream); 27 memStream.Close(); 28 return newobj; 29 }
第四、借助序列化(用到第三的方法),对象、字符串互换,代码如下:
1 /// <summary> 2 /// 对象转换成字符串 3 /// </summary> 4 /// <param name="Obj">对象</param> 5 /// <returns></returns> 6 private static string Object2String(object Obj) 7 { 8 StringBuilder sb = new StringBuilder(); 9 byte[] ByteObject = SerializeBinary(Obj); 10 foreach (byte b in ByteObject) 11 { 12 sb.Append(((int) b).ToString()); 13 sb.Append(","); 14 } 15 return sb.Remove(sb.Length - 1, 1).ToString(); 16 } 17 18 /// <summary> 19 /// 字符串转换成对象 20 /// </summary> 21 /// <param name="Value">字符串</param> 22 /// <returns></returns> 23 private static object String2Object(string Value) 24 { 25 string[] V = Value.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries); 26 byte[] ByteObject = new byte[V.Length]; 27 for (int i = 0; i < ByteObject.Length; i++) 28 { 29 ByteObject[i] = Convert.ToByte(V[i]); 30 } 31 return DeserializeBinary(ByteObject); 32 }