.NET (c#)序列化和反序列化
时间:2011-03-03 来源:just keep moving
我个人 的理解是序列化是将对象保存到文件,方便对象的传递(比如网络传输)。反序列化也就明白了,即将文件转化为对象
。反正我自己是这么理解的,好了,费话少说,上代码,欢迎拍砖
View Code1 public void SerializeToFile()
2
3 {
4
5 ClassSerialzableDemo demo = new ClassSerialzableDemo("Mr.Wang", 23);
6
7 //用BinaryFormattor序列化,文件格式可以是TXT,dat等
8
9 FileStream fs = new FileStream("BinaryFormatter.dat", FileMode.Create, FileAccess.Write);
10
11
12
13 BinaryFormatter formter = new BinaryFormatter();
14
15 formter.Serialize(fs, demo);
16
17 fs.Close();
18
19 //用XmlSerializer序列化,文件格式应该为XML
20
21
22
23 fs = new FileStream("XmlSerializer.xml", FileMode.Create, FileAccess.Write);
24
25 XmlSerializer serize = new XmlSerializer(typeof(ClassSerialzableDemo));
26
27 serize.Serialize(fs, demo);
28
29 fs.Close();
30
31
32
33 //用SoapFormater进行序列化,文件格式应该也为XML,当然不是XML也行
34
35 fs = new FileStream("SoapFormatter.xml", FileMode.Create, FileAccess.Write);
36
37 SoapFormatter forms = new SoapFormatter();
38
39 forms.Serialize(fs, demo);
40
41 fs.Close();
42
43
44
45 }
46
47 //反序列化
48
49 protected void DeSerializaFileToObject()
50
51 {
52
53
54
55 ClassSerialzableDemo demo;
56
57 FileStream fs = new FileStream("BinaryFormatter.dat", FileMode.OpenOrCreate, FileAccess.Read);
58
59 //BinaryFormater 来反序列化
60
61 BinaryFormatter formter = new BinaryFormatter();
62
63 demo = formter.Deserialize(fs) as ClassSerialzableDemo;
64
65 fs.Close();
66
67
68
69 //XmlSerializer 来反序列化
70
71 fs = new FileStream("XmlSerializer.xml", FileMode.OpenOrCreate, FileAccess.Read);
72
73 XmlSerializer xmlseria = new XmlSerializer(typeof(ClassSerialzableDemo));
74
75 demo = xmlseria.Deserialize(fs) as ClassSerialzableDemo;
76
77 fs.Close();
78
79
80
81 //SoapFormatter 来反序列化
82
83 fs = new FileStream("SoapFormatter.xml", FileMode.OpenOrCreate, FileAccess.Read);
84
85 SoapFormatter soap = new SoapFormatter();
86
87 demo = soap.Deserialize(fs) as ClassSerialzableDemo;
88
89 fs.Close();
90
91 }
92
93
94
95
96
97 using System;
98
99 using System.Collections.Generic;
100
101 using System.Linq;
102
103 using System.Text;
104
105 namespace ClassSerialzable
106
107 {
108
109 [Serializable]
110
111 public class ClassSerialzableDemo
112
113 {
114
115 /*使用 XmlSerializer时 引入 using System.Xml.Serialization;
116
117 * 1、必须要有默认构造函数
118
119 2、Serializable和NoSerialized属性将被忽略,而是使用XmlIgnore属性,它的行为与NoSerialized类似。
120
121 */
122
123 public ClassSerialzableDemo(){}
124
125 public ClassSerialzableDemo(string name, int age)
126
127 {
128
129 this.myname = name;
130
131 this.myage = age;
132
133 }
134
135 private string myname;
136
137 public string Myname
138
139 {
140
141 set { myname = value; }
142
143 get { return myname; }
144
145 }
146
147
148
149 private int myage;
150
151 public int Myage
152
153 {
154
155 set { myage = value; }
156
157 get { return myage; }
158
159 }
160
161 }
162
163 }
相关阅读 更多 +