如何检索类的所有自定义属性 [英] How can I retrieve all custom attributes on a class

查看:52
本文介绍了如何检索类的所有自定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索应用于我的类的所有属性的列表.

I'm trying to retrieve a list all attributes applied to my class.

我可以看到 Attribute.GetCustomAttributes() 系列方法,但我只能看到检索程序集、模块、成员和属性的所有属性的方法——对于类来说什么都没有.将 Type 作为参数的方法版本不合适,因为它们只返回该类型的属性,而我想按顺序遍历所有属性.

I can see the Attribute.GetCustomAttributes() series of methods, but I can only see methods to retrieve all attributes for assemblies, modules, members, and properties - nothing for a class. The versions of the method that take a Type as an argument are not appropriate because they only return attributes of that type, whereas I want to iterate through all the attributes in order.

我为什么要这样做?我正在扩展我的应用程序,并添加一些简单的 UI 模块,我想加载用户的代码,并使用属性来定义控件,例如...

Why am I doing this? I'm extending my application, and to add some simple UI mods I want to load the user's code, and use the attributes to define the controls, eg...

[MyTextBox("Address1:")]
[MyButton("QueryStatus")]
[MyButton("QuerySpeed/Pos")]
public class QueryStatus
{

我已经加载了程序集并且可以访问类 Type.还有其他地方可以找到我的所有自定义属性吗?

I've loaded the assembly and can access the class Type. Is there another place I can find all of my custom attributes?

推荐答案

只需使用 Type.GetCustomAttributes().

Type type = ...;
foreach (var attribute in type.GetCustomAttributes(inherit: false))
{
    // Whatever you need to do
}

这篇关于如何检索类的所有自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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