C# 序列化和反序列化多种类型的对象
我们有2个(或更多)课程:C# 序列化和反序列化多种类型的对象,c#,.net,serialization,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 B
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
序列化和反序列化对象(如列表)?
我不知道如何将此操作用于ArrayList和其他类似的复杂对象。这对您有用吗
[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类,您必须检查它是否可序列化。使用
DataContractSerializer
可以在列表中获取已知类型的IEnumerable
。您可以这样做,让它接受数组列表具有的任何类型:newdatacontractserializer(typeof(ArrayList),list.Select(x=>x.GetType())
。另外,为什么要在列表中混合类型?对我来说,这是一种代码气味。除非它们是从公共基类扩展而来,在这种情况下,您可以使用列表
。我检查了,您的解决方案是正确的;-)非常感谢。