2013-07-30 29 views
13

我一直在使用Reflections並希望獲取爲屬性聲明的所有屬性。 PropertInfo級別下有兩個屬性,分別爲CustomAttributesAttributes屬性與PropertyInfo中的自定義屬性

按照MSDN,它們被解釋如下:

屬性:

此屬性表示與部件相關聯的屬性。所有 成員都有一組屬性,這些屬性是根據特定類型的成員定義的。屬性屬性讓用戶知道如果 這個屬性是默認屬性,一個SpecialName屬性等等 。

注:PropertyInfo.Attributes頁面給出的示例代碼甚至不工作。

自定義屬性:

包含如果沒有屬性定義的所有應用到該 構件,或具有零個元素的數組的自定義特性的數組。

然而,當我運行此代碼對他們來說,Attributes回報什麼,而CustomAttributes回報Required

void Main() 
{ 
    var attributes = typeof(Myproperty).GetProperty("Caption").CustomAttributes; 
    //var attributes = typeof(Myproperty).GetProperty("Caption").Attributes; 
    attributes.Dump(); //Dump is a LinqPad method which dumps everything to the outpu window 
} 

public class Myproperty 
{ 
    private string caption = "Default caption"; 

    [Required] 
    public string Caption 
    { 
     get{return caption;} 
     set {if(caption!=value) {caption = value;} 
     } 
    } 
} 
+0

基本上它們在這裏的含義略有不同。這聽起來像你想要CustomAttributes。 –

+0

我發現我想要的是'CustomAttributes',但是你能解釋一下它有什麼區別嗎?國際海事組織似乎並沒有按照其名稱的意思去做。 – Tarik

+1

基本上,請參閱Hans的回答。他們是完全不同的東西。看一下MethodInfo.Attributes,這個例子對你來說可能更有意義 - 它更像是可以應用於屬性/方法等的修飾符。 –

回答

16

PropertyInfo.Attributes與Attribute類沒有任何關係。請檢查PropertyAttributes enumeration以瞭解可能遇到的值。這些是與C#代碼沒有明顯連接的CLR實現細節。是的,那是一個不幸的命名選擇。

要查找[必需的]屬性等屬性,必須使用CustomAttributes屬性。

+0

那麼也許我應該花更多的時間用於ILSpy ...... – Tarik