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

4

我们有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<>)进行序列化和反序列化?但是我不知道如何对ArrayList和其他复杂对象进行此操作。


使用 DataContractSerializer 时,构造函数有一个重载,可以将已知类型的 IEnumerable<Type> 列表作为参数。您可以使用以下代码让它接受数组列表中的任何类型: new DataContractSerializer(typeof(ArrayList), list.Select(x => x.GetType())) - Tim S.
顺便问一下,为什么你要在列表中混合使用类型?对我来说,这是一种代码异味。除非它们都继承自一个共同的基类,在这种情况下,你可以使用 List<BaseClass> - Tim S.
1个回答

4
这对您有效吗?
 [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 类,您需要检查它是否可序列化。


我已经检查过了,你的解决方案是正确的;-) 谢谢 - user2486709

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接