如何获取具有给定属性的属性列表? [英] How to get a list of properties with a given attribute?

查看:20
本文介绍了如何获取具有给定属性的属性列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型,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.

推荐答案

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

这避免了必须具体化任何属性实例(即它比 GetCustomAttribute[s]() 便宜.

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

这篇关于如何获取具有给定属性的属性列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆