特定的狀況下,可能須要將多個對象保存到文件中。在網上找了一陣,沒發現專門說這個問題的。在博問看到了一個相關的問題和回答,整理了一下。如下是個人一個簡單實現:測試
//測試用於保存的類
[Serializable]
class TestToSerizable { public int i; public string b; public TestToSerizable(int i, string b) { this.i = i; this.b = b; } } class Program { static void Main(string[] args) { TestToSerizable testa = new TestToSerizable(1, "testa"); TestToSerizable testb = new TestToSerizable(2, "testb"); TestToSerizable testc = new TestToSerizable(3, "testc");
//序列化保存多個對象 FileStream fs = new FileStream("DataFile.dat", FileMode.OpenOrCreate); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, testa); formatter.Serialize(fs, testb); formatter.Serialize(fs, testc); fs.Flush(); fs.Close();
//逆序列化讀取多個對象 fs = new FileStream("DataFile.dat", FileMode.Open); formatter = new BinaryFormatter(); TestToSerizable a = (TestToSerizable)formatter.Deserialize(fs); TestToSerizable b = (TestToSerizable)formatter.Deserialize(fs); TestToSerizable c = (TestToSerizable)formatter.Deserialize(fs); fs.Close();
Console.WriteLine("a.i=" + a.i + " a.b=" + a.b);
Console.WriteLine("b.i=" + b.i + " b.b=" + b.b);
Console.WriteLine("c.i=" + c.i + " c.b=" + c.b);this
}
}
運行結果:spa
進一步,可能會有要保存不一樣類對象的狀況。code
[Serializable] class TestToSerizableA { public int i; public string b; public TestToSerizableA(int i, string b) { this.i = i; this.b = b; } } [Serializable] class TestToSerizableB { public bool a; public float b; public TestToSerizableB(bool a, float b) { this.a = a; this.b = b; } } class Program { static void Main(string[] args) { TestToSerizableA testa = new TestToSerizableA(1, "testa"); TestToSerizableB testb = new TestToSerizableB(false, 1.23f); TestToSerizableA testc = new TestToSerizableA(3, "testc"); TestToSerizableB testd = new TestToSerizableB(true, 3.14f); //交叉保存的不一樣類型的對象 FileStream fs = new FileStream("DataFile.dat", FileMode.OpenOrCreate); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, testa); formatter.Serialize(fs, testb); formatter.Serialize(fs, testc); formatter.Serialize(fs, testd); formatter.Serialize(fs, 1);//基礎類型也能夠 fs.Flush(); fs.Close(); //按保存時的順序讀取 fs = new FileStream("DataFile.dat", FileMode.Open); formatter = new BinaryFormatter(); TestToSerizableA a = (TestToSerizableA)formatter.Deserialize(fs); TestToSerizableB b = (TestToSerizableB)formatter.Deserialize(fs); TestToSerizableA c = (TestToSerizableA)formatter.Deserialize(fs); TestToSerizableB d = (TestToSerizableB)formatter.Deserialize(fs); int i = (int)formatter.Deserialize(fs); fs.Close(); Console.WriteLine("a.i=" + a.i + " a.b=" + a.b); Console.WriteLine("b.i=" + b.a + " b.b=" + b.b); Console.WriteLine("c.i=" + c.i + " c.b=" + c.b); Console.WriteLine("d.i=" + d.a + " d.b=" + d.b); Console.WriteLine("i=" + i);
}
}
運行結果:orm
第一次寫博客,拋磚引玉,請各位前輩不吝賜教。對象
以上blog