【问题标题】:Using reflection to get each instance of XmlElementAttribute for a single property使用反射获取单个属性的每个 XmlElementAttribute 实例
【发布时间】:2011-12-05 17:04:31
【问题描述】:

我正在尝试列出 Item 可能包含的类型。但是我被困在我不能调用 Item.GetType() 来循环它的属性,因为这只会返回它已经包含的类型的属性。

我试过 TypeDescriptor.GetProperties(...) 但是属性容器只包含一个 XmlElementAttribute 的实例,这是最后一个应用于属性的实例(WindowTemplate in本例)

这一定是微不足道的,但我在网上找不到任何解决我问题的方法。

    [System.Xml.Serialization.XmlElementAttribute("ChildTemplate", typeof(ChildTmpl), Order = 1)]
    [System.Xml.Serialization.XmlElementAttribute("WindowTmeplate", typeof(WindowTmpl), Order = 1)]
    public object Item
    {
        get
        {
            return this.itemField;
        }
        set
        {
            this.itemField = value;
        }
    }

【问题讨论】:

    标签: c# .net serialization reflection allowmultiple


    【解决方案1】:

    您不能为此使用 TypeDescriptor,因为 System.ComponentModel 总是折叠属性。您必须使用PropertyInfoAttribute.GetCustomAttributes(property, attributeType)

    var property = typeof (Program).GetProperty("Item");
    Attribute[] attribs = Attribute.GetCustomAttributes(
           property, typeof (XmlElementAttribute));
    

    该数组实际上将是一个XmlElementAttribute[],如果它更容易的话:

    XmlElementAttribute[] attribs = (XmlElementAttribute[])
         Attribute.GetCustomAttributes(property, typeof (XmlElementAttribute));
    

    【讨论】:

    • 非常感谢!工作一种享受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多