序列化:就是将对象转换为二进制
反序列化:就是将二进制转换为对象。
作用:传输数据。
只有被[Serializable]标记的类才能被序列化,此类不能被继承。
Student student = new Student();
student.Name = "虎哥";
student.Age = 40;
student.Id = 1688;
//序列化实例
using (FileStream fw = new FileStream(@"D:\student.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fw, student);
}
//反序列化
using (FileStream fr = new FileStream(@"D:\student.txt", FileMode.OpenOrCreate, FileAccess.Read))
{
BinaryFormatter bn = new BinaryFormatter();
Student stu = (Student)bn.Deserialize(fr);
Console.WriteLine(stu.Name);
Console.WriteLine(stu.Age);
Console.WriteLine(stu.Id);
}