簡體   English   中英

序列化和反序列化多種類型的對象

[英]Serialize and Deserialize multiple type of Objects

我們有 2 個(或更多)類:

class numOne
{
     string name;
     int age;
}
class numTwo
{
     Bitmap pImage;
}

我有一個 ArrayList 包含這些類的實例:

ArrayList list = new ArrayList();
numOne n1 = new numOne(){ name="sth", age =18 };
numTwo n2 = new numTwo(){ pImage = new Bitmap("FileAddress") };
list.Add(n1);
list.Add(n2);

我知道我們什么時候有 A 類課程。 如何使用BinaryFormatter序列化和反序列化對象(如 List<>)? 我不知道如何將此操作用於 ArrayLists 和其他類似的復雜對象。

這對你有用嗎?

 [Serializable]
        class numOne
        {
            public string name;
            public int age;
        }
        [Serializable]
        class numTwo
        {
            public string rg;
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
//Serialization
            using (var fs = new FileStream("DataFile.dat", FileMode.Create))
            {
                var listToBeSerialized = new ArrayList(){                
                new numOne() { name = "sth", age = 18 },
                new numTwo() { rg = "FileAddress" }
            };
                new BinaryFormatter().Serialize(fs, listToBeSerialized);
            }

//Deserialization
            using (var fs = new FileStream("DataFile.dat", FileMode.Open))
            {
                var deserializedList = (ArrayList)new BinaryFormatter().Deserialize(fs);
            }
        }

對於 Bitmap 類,您必須檢查它是否可序列化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM