序列化和反序列化多种类型的对象

时间:2013-06-21 11:30:59

标签: c# .net serialization

我们有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);

我知道当我们有一种类时,我如何使用BinaryFormatter序列化和反序列化对象(如List<>)。 但是我不知道如何将这个操作用于ArrayLists以及像这样的一些复杂的目标。我该怎么办?

感谢高级......

1 个答案:

答案 0 :(得分:2)

这对你有用吗?

 [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类,您必须检查它是否可序列化。

相关问题