XmlSerializer的序列化接口的泛型列表 [英] XmlSerializer serialize generic List of interface
问题描述
我试图使用XmlSerializer的坚持一个List(T),其中T是一个接口。序列化程序不喜欢的接口。我很好奇,如果有与XmlSerializer的序列化容易异构对象列表的简单方法。下面是我要去什么:
公共接口IAnimal
{
INT年龄();
}
公共类犬:IAnimal
{
公众诠释年龄()
{
返回1;
}
}
公共类猫:IAnimal
{
公众诠释年龄()
{
返回1;
}
} 私人无效的button1_Click(对象发件人,RoutedEventArgs E)
{
VAR动物=新的List< IAnimal>
{
新狗()
新猫()
}; 变种X =新的XmlSerializer(animals.GetType());
变种B =新的StringBuilder();
变种W = XmlTextWriter.Create(B,新XmlWriterSettings {NewLineChars =\\ r \\ n,缩进=真});
//失败 - 不能序列化的界面。难道简单的方法来做到这一点存在吗?
x.Serialize(重量,动物);
变种S = b.ToString();
}
您可以使用XmlSerializer的为好,但你需要包括所有可以出现在你的序列化对象图,这限制了可扩展性,降低了可能的类型可维护性。您可以使用的XmlSerializer的构造函数的重载做到这一点:
VAR X =新的XmlSerializer(animals.GetType(),新类型[] {typeof运算(CAT)的typeof(狗)});
此外,在使用XmlSerializer的,所有列出的点击这里(MSDN) - 例如看标题动态生成的组件下
I'm trying to use the XmlSerializer to persist a List(T) where T is an interface. The serializer does not like interfaces. I'm curious if there is a simple way to serialize a list of heterogeneous objects easily with XmlSerializer. Here's what I'm going for:
public interface IAnimal
{
int Age();
}
public class Dog : IAnimal
{
public int Age()
{
return 1;
}
}
public class Cat : IAnimal
{
public int Age()
{
return 1;
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
var animals = new List<IAnimal>
{
new Dog(),
new Cat()
};
var x = new XmlSerializer(animals.GetType());
var b = new StringBuilder();
var w = XmlTextWriter.Create(b, new XmlWriterSettings { NewLineChars = "\r\n", Indent = true });
//FAIL - cannot serialize interface. Does easy way to do this exist?
x.Serialize(w, animals);
var s = b.ToString();
}
You can use XmlSerializer as well, but you need to include all the possible types that can appear in the object graph you're serializing, which limits extensibility and lowers maintainability. You can do it by using an overload of the constructor of XmlSerializer:
var x = new XmlSerializer(animals.GetType(), new Type[] { typeof(Cat), typeof(Dog) });
Also, there are several issues of note when using XmlSerializer, all of the outlined here (MSDN) - for example look under the heading 'Dynamically generated assemblies'.
这篇关于XmlSerializer的序列化接口的泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!