Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I use reflection to call all the methods that has a certain custom attribute?

I have a class with a bunch of methods.

some of these methods are marked by a custom attribute.

I would like to call all these methods at once.

How would I go about using reflection to find a list of all the methods in that class that contains this attribute?

like image 713
Diskdrive Avatar asked May 14 '10 04:05

Diskdrive


People also ask

How can you apply custom attribute?

The way to apply a Custom attribute to any part of the program you must call its constructor before the definition. NewAttribute also consists of a Parameterised constructor and a method to display the contents of the attribute.

How can you specify target for custom attribute?

Which of the following are correct ways to specify the targets for a custom attribute? A. By applying AttributeUsage to the custom attribute's class definition.

What is System reflection used for?

You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

What is the use of custom attributes?

A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.


2 Answers

Once you get the list of methods, you would cycle query for the custom attributes using the GetCustomAttributes method. You may need to change the BindingFlags to suit your situation.

var methods = typeof( MyClass ).GetMethods( BindingFlags.Public );

foreach(var method in methods)
{
    var attributes = method.GetCustomAttributes( typeof( MyAttribute ), true );
    if (attributes != null && attributes.Length > 0)
        //method has attribute.

}
like image 129
Thomas Avatar answered Sep 22 '22 18:09

Thomas


First, you would call typeof(MyClass).GetMethods() to get an array of all the methods defined on that type, then you loop through each of the methods it returns and call methodInfo.GetCustomAttributes(typeof(MyCustomAttribute), true) to get an array of custom attributes of the specified type. If the array is zero-length then your attribute is not on the method. If it's non-zero, then your attribute is on that method and you can use MethodInfo.Invoke() to call it.

like image 6
Dean Harding Avatar answered Sep 20 '22 18:09

Dean Harding