Xml 序列化后代列表

发布于 2024-12-23 13:31:39 字数 525 浏览 2 评论 0原文

我正在尝试序列化后代列表。这就是我现在所拥有的,工作正常:

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 Animals. 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 XmlArrayItems 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

滥情稳全场 2024-12-30 13:31:39

您可以在程序集中获取派生类型的列表,如下所示:

public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
    var types = Assembly.GetAssembly(type).GetTypes();
    return types.Where(t => t.IsSubclassOf(type));
}

也许您可以在上面的 GetAllTypesDerivedFrom 方法上循环执行 foreach 循环,然后将其放入类似于 MSDN 示例的解决方案中 XmlArrayItems

注意:如果您需要获取接口的所有派生类型,则需要使用以下内容(适用于接口和类):

return types.Where(type.IsAssignableFrom).Where(t => t != type);

You can get a list of derived types within an assembly like so:

public IEnumerable<Type> GetAllTypesDerivedFrom(Type type)
{
    var types = Assembly.GetAssembly(type).GetTypes();
    return types.Where(t => t.IsSubclassOf(type));
}

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):

return types.Where(type.IsAssignableFrom).Where(t => t != type);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文