序列化和反序列化示例
虽然是很简单的一段代码,但由于我把第10行的位置写错了,害的我调试了N次才找到原因。
代码
1 object TabObj = this.GetObjectValue(TargetObj); // 这是要序列化的值
2 byte[] Value = null;
3
4 BinaryFormatter formatter = new BinaryFormatter();
5 // 序列化
6 using (Stream stream = new MemoryStream())
7 {
8 //formater.Serialize(stream, iid);
9 formatter.Serialize(stream, TabObj);
10 Value = new byte[stream.Length];
11 stream.Seek(0, SeekOrigin.Begin);
12 stream.Read(Value, 0, (int)stream.Length);
13 }
14
15 //
16 #region 反序列化
17 using (Stream sm = new MemoryStream())
18 {
19 sm.Write(Value,0,Value.Length);
20 sm.Seek(0, SeekOrigin.Begin);
21 object obj = formatter.Deserialize(sm);
22 }
23 #endregion
2 byte[] Value = null;
3
4 BinaryFormatter formatter = new BinaryFormatter();
5 // 序列化
6 using (Stream stream = new MemoryStream())
7 {
8 //formater.Serialize(stream, iid);
9 formatter.Serialize(stream, TabObj);
10 Value = new byte[stream.Length];
11 stream.Seek(0, SeekOrigin.Begin);
12 stream.Read(Value, 0, (int)stream.Length);
13 }
14
15 //
16 #region 反序列化
17 using (Stream sm = new MemoryStream())
18 {
19 sm.Write(Value,0,Value.Length);
20 sm.Seek(0, SeekOrigin.Begin);
21 object obj = formatter.Deserialize(sm);
22 }
23 #endregion