Xml 序列化后代列表
我正在尝试序列化后代列表。这就是我现在所拥有的,工作正常:
class Animal {}
class Zebra:Animal{}
class Hippo:Animal{}
[XmlRootAttribute("Zoo")]
class Zoo
{
[XmlArrayItem(typeof(Zebra))]
[XmlArrayItem(typeof(Hippo))]
public List<Animal> Actions
{ set; get; }
}
这工作正常,我可以序列化两个 Animal
。我想知道是否可以创建一个 Attribute
类,我可以在其中传递动物(实例)列表,并为我创建 XmlArrayItem
属性。
一般来说,我正在寻找一种方法来避免每次创建新动物时都指定 Animal
的后代。我希望 Animal
的所有后代都被序列化,无论其类型如何。
I am trying to serialize a list of descendants. This is what I have now, that works fine:
class Animal {}
class Zebra:Animal{}
class Hippo:Animal{}
[XmlRootAttribute("Zoo")]
class Zoo
{
[XmlArrayItem(typeof(Zebra))]
[XmlArrayItem(typeof(Hippo))]
public List<Animal> Actions
{ set; get; }
}
This works fine and I can serialize both Animal
s. I wonder If it is possible to create an Attribute
class where I can pass the list of animals (instances), and will create for me the XmlArrayItem
s attributes.
In general, I am looking for a way to avoid specifying the descendants of Animal
everytime I create a new one. I want all descendants of Animal
to be serialized, whatever their type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在程序集中获取派生类型的列表,如下所示:
也许您可以在上面的 GetAllTypesDerivedFrom 方法上循环执行 foreach 循环,然后将其放入类似于 MSDN 示例的解决方案中 XmlArrayItems。
注意:如果您需要获取接口的所有派生类型,则需要使用以下内容(适用于接口和类):
You can get a list of derived types within an assembly like so:
Perhaps you can cycle through a foreach loop on the GetAllTypesDerivedFrom method above, and then fit it into a solution similar to the MSDN example for XmlArrayItems.
NOTE: If you need to get all derived types for an interface, you'll instead need to use the following (would work with both interfaces and classes):