什么是序列化:保存一个数据,直接将内存中的数据原封不动的或按照某种特定格式的形式抠出来(这种数据我们人类是无法识别,但计算机可以,而且不需要经过太多转换)
序列化定义:二进制序列化(将内存中的对象直接以二进制的形式取出)
步骤
-> 创建一个文件流
-> 确保对象可以被序列化,给类前面加上[Serializable]
-> BinaryFormatter
-> Serialize()方法
反序列化定义:将文本文件的数据映射成相应的内存数据
方法与步骤与序列化相同,唯一不同的是调用Deserialize方法
XML序列化中常用(以后介绍)
案例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 |
static
void Main( string [] args) { #region 序列化对象 Person p1 = new
Person(); p1.Name = "dongqing" ; p1.Age = 20; p1.Gender = ‘男‘ ; //先创建一个文件流 using
(FileStream fwrite = new
FileStream( "peson_info.txt" , FileMode.Create, FileAccess.Write)) { //创建序列化与反序列化对象(这个就相当于一个工具,通过它可以把对象进行序列化或者反序列化) BinaryFormatter bf = new
BinaryFormatter(); //序列化对象,并把序列化好的数据写到文件中 bf.Serialize(fwrite, p1); } #endregion #region 反序列化 Person p2; //先创建一个文件流 using
(FileStream fwrite = new
FileStream( "peson_info.txt" , FileMode.Open, FileAccess.Read)) { //创建序列化与反序列化对象(这个就相当于一个工具,通过它可以把对象进行序列化或者反序列化) BinaryFormatter bf = new
BinaryFormatter(); //序列化对象,并把序列化好的数据写到文件中 p2 = bf.Deserialize(fwrite) as
Person; } if
(p2 != null ) { Console.WriteLine(p2.Name+ " " +p2.Age+ " " +p2.Gender); } #endregion Console.ReadKey(); } |
Person.cs
[Serializable] //可被序列化标记 public class Person { string _name; int _age; char _gender; public Person() { } public Person(string name, int age, char gender) { this._name = name; this._age = age; this._gender = gender; } public string Name { get { return _name; } set { _name = value; } } public int Age { get { return _age; } set { _age = value; } } public char Gender { get { return _gender; } set { _gender = value; } } }
原文:http://www.cnblogs.com/dongqinglove/p/3541806.html