2011-10-11 16 views
3

我試圖列出項目可能包含的可能類型。但是我陷入了困境,我無法調用Item.GetType()來遍歷它的Attributes,因爲這隻會返回它已經包含的類型的屬性。使用反射爲單個屬性獲取XmlElementAttribute的每個實例

我已經試過TypeDescriptor.GetProperties(...)但屬性容器只包含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; 
     } 
    } 

回答

6

您不能對此使用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)); 
+0

非常感謝您!作品一種享受。 – Jaaaaaay

相關問題