所谓对象序列化Serialization,是指将对象保存到流Steam中(一般是磁盘文件数据流,可以使对象“永生”),需要时可以从流中重新读取数据重建对象(称为反序列化Deserialization)。
(1)定义被序列化的类,即加上[Serializable]属性。如
[SerializableAttribute]
public class Student
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
public void SayHi()
{
Console.WriteLine("Hi,My name is {0}.",Name);
}
}
(2)调用BinaryFormatter类的Serialize方法进行序列化。如
public static void Save(Student s)
{
using (FileStream fileStream = new FileStream("profile.bin", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fileStream, s);
fileStream.Close();
}
}
(3)调用BinaryFormatter类的Deserialize方法进行反序列化。如
public static Student Load()
{
Student s = new Student();
using (FileStream fileStream = new FileStream("profile.bin", FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
s= (Student)bf.Deserialize(fileStream);
fileStream.Close();
}
return s;
}
(4)需要时可以调用上面的方法,进行序列化和反序列化:
static void Main(string[] args)
{
Student s = new Student();
s.Name = "aa";
Save(s);
Student otherStudent = Load();
otherStudent.SayHi();
Console.ReadKey();
}
在这过程中需要引用命名空间:
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;