文件序列化和反序列化
序列化是把对象以二进制的形式存在文件中
List<Person> ps = new List<Person>(); ps.Add(new Person("张三", 12, '男')); //能不能直接把对象,以二进制的形式存在文件中呢? FileStream fs = new FileStream(@"d:\序列化", FileMode.Create, FileAccess.Write); using (fs) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(fs, ps); }
反序列化:
FileStream fs = new FileStream(@"d:\序列化", FileMode.Open, FileAccess.Read); List<Person> ps; using (fs) { BinaryFormatter bf = new BinaryFormatter(); ps = (List<Person>)bf.Deserialize(fs); }
注意:要序列化类必须打上 [Serializable]
[Serializable] class Person { private string name; private int age; private char sex; public Person(string name, int age, char sex) { this.name = name; this.age = age; this.sex = sex; } public void SayHello() { Console.WriteLine("大家好,我是{0},今年{1}岁了,我是{2}生",name,age,sex); } public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public char Sex { get { return sex; } set { sex = value; } } }