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

2

6

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?

Medieval answered 14/5, 2010 at 4:19 Comment(0)
L
7

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.

}
Lacylad answered 14/5, 2010 at 4:26 Comment(0)
S
6

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.

Schumann answered 14/5, 2010 at 4:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.