2012-02-29 67 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();