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 c开发者_StackOverflow社区annot 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;
}
}
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));
精彩评论