2011-05-09 60 views
8

我正在嘗試爲webform項目創建自定義屬性驗證。PropertyInfo - 具有屬性的GetProperties

我已經可以從我的類中獲取所有屬性,但現在我不知道如何過濾它們並獲取具有某些屬性的屬性。

例如:

PropertyInfo[] fields = myClass.GetType().GetProperties(); 

這將返回我的所有屬性。但是,我怎樣才能返回屬性像「testAttribute」,例如?

我已經搜查了這個,但經過幾次試圖解決這個問題,我決定在這裏問。

回答

9
fields.Where(pi => pi.GetCustomAttributes(typeof(TestAttribute), false).Length > 0) 

請參閱documentation for GetCustomAttributes()

+0

謝謝。我試圖使用GetCostumAttributes,但我沒有使長度> 0的條件。你解決了它的隊友;) – 2011-05-09 23:14:24

1

您可能需要MemberInfo的GetCustomAttributes方法。如果你特別爲說,TestAttribute看,你可以使用:

foreach (var propInfo in fields) { 
    if (propInfo.GetCustomAttributes(typeof(TestAttribute), false).Count() > 0) { 
     // Do some stuff... 
    }  
} 

或者,如果你只是需要把他們都弄到:

var testAttributes = fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Count() > 0); 
+1

使用任何()而不是Count()> 0 – 2014-03-25 01:06:04

23

使用Attribute.IsDefined

PropertyInfo[] fields = myClass.GetType().GetProperties() 
    .Where(x => Attribute.IsDefined(x, typeof(TestAttribute), false)) 
    .ToArray(); 
+0

這是一個更好的答案:當我們只需要一個存在檢查時不需要計數。 – Askolein 2013-03-25 11:34:57

2

你可以使用

.Any() 

並簡化表達式

fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any()) 
相關問題