【问题标题】:Xml Serialize List of DescendantsXml 序列化后代列表
【发布时间】:2012-01-31 08:54:14
【问题描述】:

我正在尝试序列化后代列表。这就是我现在所拥有的,效果很好:

class Animal {}
class Zebra:Animal{}
class Hippo:Animal{}

[XmlRootAttribute("Zoo")] 
class Zoo
{
    [XmlArrayItem(typeof(Zebra))]
    [XmlArrayItem(typeof(Hippo))]
    public List<Animal> Actions
    { set; get; }
}

这很好用,我可以同时序列化Animals。我想知道是否可以创建一个 Attribute 类,我可以在其中传递动物(实例)列表,并为我创建 XmlArrayItems 属性。

一般来说,我正在寻找一种方法来避免每次创建新的时都指定Animal 的后代。我希望Animal 的所有后代都被序列化,无论其类型如何。

【问题讨论】:

    标签: c# serialization .net-3.5 xml-serialization


    【解决方案1】:

    您可以像这样在程序集中获取派生类型的列表:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多