【问题标题】:Serialize and Deserialize multiple type of Objects序列化和反序列化多种类型的对象
【发布时间】:2013-06-21 11:30:59
【问题描述】:

我们有 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 序列化和反序列化对象(如列表)? 我不知道如何将这个操作用于 ArrayLists 和其他类似的复杂对象。

【问题讨论】:

  • 对于DataContractSerializer,有一个overload of the constructor,它采用列表中已知类型的IEnumerable<Type>。您可以这样做以使其采用数组列表具有的任何类型:new DataContractSerializer(typeof(ArrayList), list.Select(x => x.GetType()))
  • 顺便说一句,您为什么要在列表中混合类型?对我来说,这是一种代码味道。除非它们从公共基类扩展,在这种情况下您可以使用 List<BaseClass>

标签: c# .net serialization


【解决方案1】:

这对你有用吗?

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

【讨论】:

  • 我检查了,您的解决方案是正确的 ;-) 谢谢
猜你喜欢
  • 2015-12-22
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 2016-10-14
  • 2014-12-24
相关资源
最近更新 更多