How to use reflection to call all methods that have a specific user attribute?

I have a class with a bunch of methods.

some of these methods are marked with a special attribute.

I would like to call all these methods right away.

How can I use reflection to find a list of all the methods in this class that contains this attribute?

+6
reflection c # attributes
source share
2 answers

Once you get the list of methods, you will loop through the query for 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. } 
+7
source share

First you call typeof (MyClass) .GetMethods () to get an array of all the methods defined for this type, then you loop through each of the returned methods and call methodInfo.GetCustomAttributes (typeof (MyCustomAttribute), true) to get an array of user attributes specified type. If the array is zero length, your attribute is not in the method. If it is nonzero, then your attribute is in this method, and you can use MethodInfo.Invoke () to call it.

+6
source share

All Articles