8

我正在尝试为 webform 项目创建自定义属性验证。

我已经可以从我的类中获取所有属性,但现在我不知道如何过滤它们,只获取具有某些属性的属性。

例如:

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

这将返回我所有的属性。但是,例如,我如何才能使用“testAttribute”之类的属性返回属性?

我已经对此进行了搜索,但是经过几次尝试解决此问题后,我决定在这里问。

4

4 回答 4

24

使用Attribute.IsDefined

PropertyInfo[] fields = myClass.GetType().GetProperties()
    .Where(x => Attribute.IsDefined(x, typeof(TestAttribute), false))
    .ToArray();
于 2011-05-09T23:16:07.513 回答
10
fields.Where(pi => pi.GetCustomAttributes(typeof(TestAttribute), false).Length > 0)

参阅GetCustomAttributes().

于 2011-05-09T23:09:22.760 回答
3

您可以使用

    .Any()

并简化表达

    fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any())
于 2013-07-31T09:48:16.127 回答
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);
于 2011-05-09T23:09:56.760 回答