我正在尝试为 webform 项目创建自定义属性验证。
我已经可以从我的类中获取所有属性,但现在我不知道如何过滤它们,只获取具有某些属性的属性。
例如:
PropertyInfo[] fields = myClass.GetType().GetProperties();
这将返回我所有的属性。但是,例如,我如何才能使用“testAttribute”之类的属性返回属性?
我已经对此进行了搜索,但是经过几次尝试解决此问题后,我决定在这里问。
我正在尝试为 webform 项目创建自定义属性验证。
我已经可以从我的类中获取所有属性,但现在我不知道如何过滤它们,只获取具有某些属性的属性。
例如:
PropertyInfo[] fields = myClass.GetType().GetProperties();
这将返回我所有的属性。但是,例如,我如何才能使用“testAttribute”之类的属性返回属性?
我已经对此进行了搜索,但是经过几次尝试解决此问题后,我决定在这里问。
使用Attribute.IsDefined
:
PropertyInfo[] fields = myClass.GetType().GetProperties()
.Where(x => Attribute.IsDefined(x, typeof(TestAttribute), false))
.ToArray();
fields.Where(pi => pi.GetCustomAttributes(typeof(TestAttribute), false).Length > 0)
您可以使用
.Any()
并简化表达
fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any())
您可能需要 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);