View Code
要在序列化的类上加一个特性: [Serializable]
Student 类
[Serializable] class Student { public Student(string name,int age) { this.name = name; this.age = age; } private Dog dog; internal Dog Dog { get { return dog; } set { dog = value; } } private string name; public string Name { get { return name; } set { name = value; } } private int age; public int Age { get { return age; } set { age = value; } } [Obsolete("这个方法是已经过时的方法,请使用SayHello代替")] public void SayHi() { Console.WriteLine("姓名:{0},年龄:{1}",name,age); } }
序列化
Student stu = new Student("拉登", 18); Student stu1 = new Student("布什", 18); Student stu2 = new Student("萨达姆", 18); List<Student> students = new List<Student>(); students.Add(stu); students.Add(stu1); students.Add(stu2); //序列化 using (FileStream fs = new FileStream("stus", FileMode.Create)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, students); }
反序列化
using (FileStream fs = new FileStream("stus", FileMode.Open)) { BinaryFormatter bf = new BinaryFormatter(); List<Student> stus = bf.Deserialize(fs) as List<Student>; if (stus != null) { foreach (Student item in stus) { item.SayHi(); } } }