例子:(见书P298) using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Permissions; namespace ConsoleApplication2 { /// <summary> /// 自定义序列化类 /// </summary> [Serializable] public class Employee : ISerializable { public int EmpId = 100; public string EmpName = "小王"; public Employee() { } private Employee(SerializationInfo info, StreamingContext ctxt) { EmpId = (int)info.GetValue("EmployeeId", typeof(int)); EmpName = (string)info.GetValue("EmployeeName", typeof(string)); } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("EmployeeId", EmpId); info.AddValue("EmployeeName", EmpName); } } public class Test { /// <summary> /// BinaryFormatter 进行序列化 /// </summary> public void DoSerialize() { Employee mp = new Employee(); mp.EmpId = 10; mp.EmpName = "小张"; Stream stream = File.Open("c://Employee.dat", FileMode.Create); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, mp); stream.Close(); } /// <summary> /// BinaryFormatter 进行反序列化 /// </summary> public void DoDeserialize() { Stream stream = File.Open("c://Employee.dat", FileMode.Open); BinaryFormatter bf = new BinaryFormatter(); Employee mp = (Employee)bf.Deserialize(stream); stream.Close(); Console.WriteLine(mp.EmpId); Console.WriteLine(mp.EmpName); } static void Main(string[] args) { Test test = new Test(); test.DoSerialize(); test.DoDeserialize(); } } }