如何获得的属性与给定的属性列表? [英] How to get a list of properties with a given attribute?
问题描述
我有型, T
,我想获得具有属性的公共属性列表 MyAttribute
。该属性标记的AllowMultiple = FALSE
,像这样的:
I have a type, t
, and I would like to get a list of the public properties that have the attribute MyAttribute
. The attribute is marked with AllowMultiple = false
, like this:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
目前我有什么是这样的,但我想有一个更好的方法:
Currently what I have is this, but I'm thinking there is a better way:
foreach (PropertyInfo prop in t.GetProperties())
{
object[] attributes = prop.GetCustomAttributes(typeof(MyAttribute), true);
if (attributes.Length == 1)
{
//Property with my custom attribute
}
}
如何改进呢?我的道歉,如果这是一个重复的,有一吨的反射线有...好像它是一个相当热门的话题。
How can I improve this? My apologies if this is a duplicate, there are a ton of reflection threads out there...seems like it's quite a hot topic.
推荐答案
我最终会使用最该解决方案基于断托马斯Petricek的回答。我通常会想做些什么的两个的属性和属性。
The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with both the attribute and property.
var props = from p in this.GetType().GetProperties()
let attr = p.GetCustomAttributes(typeof(MyAttribute), true)
where attr.Length == 1
select new { Property = p, Attribute = attr.First() as MyAttribute};
这篇关于如何获得的属性与给定的属性列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!