using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; //using System.Runtime.Serialization.Formatters.Binary; namespace 序列化与反序列化 { class Program { public static void Main(String[] args) { //序列化 //Person p = new Person(); //p.Name = "张三"; //p.Age = 20; //p.Gender = 'f'; //using (FileStream fswrite = new FileStream(@"f:\Person.txt", FileMode.CreateNew, FileAccess.Write)) { // BinaryFormatter bf = new BinaryFormatter(); // bf.Serialize(fswrite,p); //} //反序列化 Person p; using (FileStream fsread = new FileStream(@"f:\Person.txt", FileMode.Open, FileAccess.Read)) { BinaryFormatter bf = new BinaryFormatter(); p = bf.Deserialize(fsread) as Person; } Console.WriteLine(p.Name); Console.WriteLine(p.Age); Console.WriteLine(p.Gender); } } [Serializable] class Person { private string _name; private int _age; private char _gender; public string Name { get => _name; set => _name = value; } public int Age { get => _age; set => _age = value; } public char Gender { get => _gender; set => _gender = value; } } }