PropertyInfo - 具有属性的GetProperties

时间:2011-05-09 22:54:42

标签: c# system.reflection

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

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

例如:

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

这将返回所有属性。但是,我如何使用像“testAttribute”这样的属性返回属性,例如?

我已经搜索了这个,但经过几次尝试解决这个问题后,我决定在这里问一下。

4 个答案:

答案 0 :(得分:23)

使用Attribute.IsDefined

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

答案 1 :(得分:9)

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

请参阅documentation for GetCustomAttributes()

答案 2 :(得分:2)

您可以使用

    .Any()

并简化表达

    fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any())

答案 3 :(得分: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);
相关问题