问题
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