Invoking Static Methods with Reflection
Problem:
You possess several static classes within the namespace mySolution.Macros, each containing static methods like:
public static class Indent { public static void Run() { // implementation } }
Your objective is to invoke these methods using reflection, even though they are static.
Solution:
To invoke static methods with reflection while preserving their static nature, employ the following approach:
foreach (var tempClass in macroClasses) { // Note that the first argument is ignored for static methods tempClass.GetMethod("Run").Invoke(null, null); }
As mentioned in the documentation for MethodInfo.Invoke, the first argument is redundant for static methods, so you can safely pass null.
Binding Flags:
It is important to note that you may need to specify binding flags when invoking the method, as suggested in the comment:
tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
This ensures that the method is public and static, which is necessary for proper invocation.
The above is the detailed content of How to Invoke Static Methods Using Reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!