我正在尝试为webform项目创建自定义属性验证。
我已经可以从我的类中获取所有属性,但现在我不知道如何过滤它们,只获取具有某些属性的属性。
例如:
PropertyInfo[] fields = myClass.GetType().GetProperties();这将返回我所有的属性。但是,例如,我如何使用"testAttribute“这样的属性来返回属性呢?
我已经对这个问题进行了搜索,但在尝试解决这个问题后,我决定在这里提问。
发布于 2011-05-10 07:09:23
fields.Where(pi => pi.GetCustomAttributes(typeof(TestAttribute), false).Length > 0)参见documentation for GetCustomAttributes()。
发布于 2011-05-10 07:16:08
使用Attribute.IsDefined
PropertyInfo[] fields = myClass.GetType().GetProperties()
.Where(x => Attribute.IsDefined(x, typeof(TestAttribute), false))
.ToArray();发布于 2013-07-31 17:48:16
您可以使用
.Any()和简化表达式
fields.Where(x => x.GetCustomAttributes(typeof(TestAttribute), false).Any())https://stackoverflow.com/questions/5943408
复制相似问题