應用程序有時需要以對象的形式在磁盤上存儲數據,FrameWork有兩個可用的實現方式:
一:System.Runtime.Serialization.Formatters.Binarry這個名稱空間包含了BinarryFormatter類,它能把對象序列化為二進制數據,把二進制數據序列化為對象
二:System.Runtime.Serialization.Formatters.Soap:這個名稱空間中包含了類SoapFormat類,它能把對象序列化為Soap格式的XML數據
以上兩個類都實現了IFormatter接口,IFormatter接口提供了下面兩個方法:
BinaryFormatter序列化、反序列化對象
[Serializable] class Test { public long Id; public string Name; public double Price; [NonSerialized] string Notes; public Test(long id, string name, double price, string notes) { this.Id = id; this.Name = name; this.Price = price; this.Notes = notes; } public override string ToString() { return string.Format("{0}:{1} (${2:F2}) {3}", Id, Name, Price, Notes); }
static void Main(string[] args) { List<Test> tests = new List<Test>(); tests.Add(new Test(1, "蘋果", 5.5, "煙台紅富士")); tests.Add(new Test(2, "菠蘿", 3.5, "海南菠蘿")); tests.Add(new Test(3, "櫻桃", 100, "智利櫻桃")); //用於序列化和反序列化的對象 IFormatter serializer = new BinaryFormatter(); //開始序列化 FileStream saveFile = new FileStream("Test.txt", FileMode.Create, FileAccess.Write); serializer.Serialize(saveFile, tests); saveFile.Close(); //反序列化 FileStream loadFile = new FileStream("Test.txt", FileMode.Open, FileAccess.Read); List<Test> tests2 = serializer.Deserialize(loadFile) as List<Test>; foreach (Test item in tests2) { Console.WriteLine(item); } Console.ReadKey(); }