2012-07-30 38 views
1

我有3個屬性的類。如何通過自定義屬性來選擇某個屬性的某些屬性

class Issuance 
{ 
    [MyAttr] 
    virtual public long Code1 { get; set; } 

    [MyAttr] 
    virtual public long Code2 { get; set; } 

    virtual public long Code3 { get; set; } 
} 

我需要我的自定義屬性([MyAttr])選擇一些在這個類的屬性。

我使用GetProperties()但是這返回所有屬性。

var myList = new Issuance().GetType().GetProperties(); 
//Count of result is 3 (Code1,Code2,Code3) But count of expected is 2(Code1,Code2) 

我該怎麼辦?

+1

您需要在每個屬性上使用GetCustomAttributes並檢查返回的屬性是否屬於MyAttr類型。 – Charleh 2012-07-30 14:27:54

回答

8

只需使用LINQ和使用MemberInfo.IsDefined一個Where條款:

var myList = typeof(Issuance).GetProperties() 
          .Where(p => p.IsDefined(typeof(MyAttr), false); 
+1

這真是太棒了Jon,我不認爲我曾經使用過IsDefined - 這只是GetCustomAttributes的包裝? – Charleh 2012-07-30 14:33:27

+0

@Charleh:我不知道 - 但它確實更簡單:) – 2012-07-30 14:34:55

+0

好吧,任何削減代碼行的東西都會讓我的投票! – Charleh 2012-07-30 14:36:21

0

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getcustomattributes.aspx

試試這個 - 基本上做的屬性在foreach,看你回來爲每個屬性的屬性類型。如果這樣做,那麼該屬性具有以下屬性:

foreach(var propInfo in new Issuance().GetType().GetProperties()) 
{ 
    var attrs = propInfo.GetCustomAttributes(typeof(MyAttr), true/false); // Check docs for last param 

    if(attrs.Count > 0) 
     // this is one, do something 
}