Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to list the possible types that Item could contain. However I am stuck in that I can't call Item.GetType() to loop through its Attributes as this would just return the attributes of the type that it already contained.

I have tried TypeDescriptor.GetProperties(...) but the Attributes container only contains one instance of XmlElementAttribute which is the last one applied to the property (WindowTemplate in this case)

This must be trivial but I cannot find any solution to my problem online.

    [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;
        }
    }
like image 431
Jaaaaaay Avatar asked Sep 01 '25 10:09

Jaaaaaay


1 Answers

You can't use TypeDescriptor for this, as System.ComponentModel always collapses attributes. You must use PropertyInfo and Attribute.GetCustomAttributes(property, attributeType):

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

the array will actually be a XmlElementAttribute[] if it makes it easier:

XmlElementAttribute[] attribs = (XmlElementAttribute[])
     Attribute.GetCustomAttributes(property, typeof (XmlElementAttribute));
like image 106
Marc Gravell Avatar answered Sep 04 '25 10:09

Marc Gravell