加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Xml Serialize Descendants列表

发布时间:2020-12-15 08:02:50 所属栏目:百科 来源:网络整理
导读:我正在尝试序列化后代列表.这就是我现在所做的,效果很好: class Animal {}class Zebra:Animal{}class Hippo:Animal{}[XmlRootAttribute("Zoo")] class Zoo{ [XmlArrayItem(typeof(Zebra))] [XmlArrayItem(typeof(Hippo))] public ListAnimal Actions { set;
我正在尝试序列化后代列表.这就是我现在所做的,效果很好:
class Animal {}
class Zebra:Animal{}
class Hippo:Animal{}

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

这工作正常,我可以序列化两个动物.我想知道是否有可能创建一个Attribute类,我可以在其中传递动物(实例)列表,并为我创建XmlArrayItems属性.

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

解决方法

您可以在程序集中获取派生类型的列表,如下所示:
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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读