How can I retrieve all custom attributes on a class

放肆的年华 提交于 2019-12-25 07:20:10

问题


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

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.

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
{

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


回答1:


Just use Type.GetCustomAttributes().

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


来源:https://stackoverflow.com/questions/16495886/how-can-i-retrieve-all-custom-attributes-on-a-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!