2012-02-29 62 views
3

内一类,我有以下的一段代码:查看/检索属性

/// <remarks/> 
[System.Xml.Serialization.XmlElementAttribute("Errors", typeof(ErrorsType))] 
[System.Xml.Serialization.XmlElementAttribute("Success", typeof(SuccessType))] 
[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))] 
public object[] Items { 
    get { 
     return this.itemsField; 
    } 
    set { 
     this.itemsField = value; 
    } 
} 

只使用反射,是有可能检索这些属性? 我看到'GetCustomAttributes()在各自的Type,但没有得到太多的喜悦。

回答

4

您需要检索从属性的属性,而不是类型本身,就像这样:

typeof(MyClass).GetProperty("Items").GetCustomAttributes(typeof(XmlElementAttribute), false); 

或多个完整的(记得要导入System.Linq的为铸造<>和ToArray的()工作) :

XmlElementAttribute[] attribs = typeof(TheType) 
        .GetProperty("Items") 
        .GetCustomAttributes(typeof(XmlElementAttribute), false) 
        .Cast<XmlElementAttribute>() 
        .ToArray();