C# Xml序列化子体列表
我正在尝试序列化后代的列表。这就是我现在拥有的,效果很好:C# Xml序列化子体列表,c#,serialization,.net-3.5,xml-serialization,C#,Serialization,.net 3.5,Xml Serialization,我正在尝试序列化后代的列表。这就是我现在拥有的,效果很好: class Animal {} class Zebra:Animal{} class Hippo:Animal{} [XmlRootAttribute("Zoo")] class Zoo { [XmlArrayItem(typeof(Zebra))] [XmlArrayItem(typeof(Hippo))] public List<Animal> Actions { set; get;
class Animal {}
class Zebra:Animal{}
class Hippo:Animal{}
[XmlRootAttribute("Zoo")]
class Zoo
{
[XmlArrayItem(typeof(Zebra))]
[XmlArrayItem(typeof(Hippo))]
public List<Animal> Actions
{ set; get; }
}
类动物{}
斑马类:动物{}
河马类:动物{}
[XmlRootAttribute(“Zoo”)]
班级动物园
{
[XmlArrayItem(typeof(斑马))]
[XmlArrayItem(类型(河马))]
公开名单行动
{set;get;}
}
这很好,我可以序列化Animal
s。我想知道是否可以创建一个属性
类,在该类中我可以传递动物列表(实例),并将为我创建XmlArrayItem
s属性
一般来说,我正在寻找一种方法来避免每次创建新的
Animal
的后代。我希望对Animal
的所有后代进行序列化,无论其类型如何。您可以在程序集中获得派生类型列表,如下所示:
public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
var types = Assembly.GetAssembly(type).GetTypes();
return types.Where(t => t.IsSubclassOf(type));
}
return types.Where(type.IsAssignableFrom).Where(t => t != type);