C# 如何获取具有给定属性的属性列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2281972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:01:38  来源:igfitidea点击:

How to get a list of properties with a given attribute?

c#.netreflection

提问by wsanville

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:

我有一个类型 ,t并且我想获取具有属性 的公共属性的列表MyAttribute。该属性用 标记AllowMultiple = false,如下所示:

[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.

我该如何改进?如果这是重复的,我很抱歉,那里有大量的反射线程......似乎这是一个非常热门的话题。

采纳答案by Marc Gravell

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

这避免了必须实现任何属性实例(即它比GetCustomAttribute[s]().

回答by Tomas Petricek

As far as I know, there isn't any better way in terms of working with Reflection library in a smarter way. However, you could use LINQ to make the code a bit nicer:

据我所知,在以更智能的方式使用反射库方面没有更好的方法。但是,您可以使用 LINQ 使代码更好一点:

var props = from p in t.GetProperties()
            let attrs = p.GetCustomAttributes(typeof(MyAttribute), true)
            where attrs.Length != 0 select p;

// Do something with the properties in 'props'

I believe this helps you to structure the code in a more readable fashion.

我相信这可以帮助您以更具可读性的方式构建代码。

回答by P Daddy

There's always LINQ:

总是有 LINQ:

t.GetProperties().Where(
    p=>p.GetCustomAttributes(typeof(MyAttribute), true).Length != 0)

回答by flq

If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:

如果你经常处理反射中的属性,定义一些扩展方法是非常非常实用的。你会在很多项目中看到这一点。这是我经常遇到的一个:

public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
  var atts = provider.GetCustomAttributes(typeof(T), true);
  return atts.Length > 0;
}

which you can use like typeof(Foo).HasAttribute<BarAttribute>();

你可以像这样使用 typeof(Foo).HasAttribute<BarAttribute>();

Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:

其他项目(例如 StructureMap)具有成熟的 ReflectionHelper 类,这些类使用表达式树来具有用于标识的精细语法,例如 PropertyInfos。用法如下所示:

ReflectionHelper.GetProperty<Foo>(x => x.MyProperty).HasAttribute<BarAttribute>()

回答by wsanville

The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with boththe attribute and property.

我最终使用最多的解决方案是基于 Tomas Petricek 的回答。通常我想要做的东西属性和属性。

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};

回答by feeeper

In addition to previous answers: it's better to use method Any()instead of check length of the collection:

除了以前的答案:最好使用方法Any()而不是检查集合的长度:

propertiesWithMyAttribute = type.GetProperties()
  .Where(x => x.GetCustomAttributes(typeof(MyAttribute), true).Any());

The example at dotnetfiddle: https://dotnetfiddle.net/96mKep

dotnetfiddle 的示例:https://dotnetfiddle.net/96mKep