繁体   English   中英

使用反射为单个属性获取XmlElementAttribute的每个实例

[英]Using reflection to get each instance of XmlElementAttribute for a single property

我正在尝试列出Item可能包含的可能类型。 但是我陷入困境,我无法调用Item.GetType()来遍历其属性,因为这只会返回它已经包含的类型的属性。

我尝试过TypeDescriptor.GetProperties(...)但是Attributes容器只包含一个XmlElementAttribute实例,它是应用于属性的最后一个实例(在本例中为WindowTemplate)

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

    [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;
        }
    }

您不能使用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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM