Dynamically Accessing and Invoking Static C# Methods via Reflection
Imagine you have a class name stored as a string (e.g., "MyClass") and need to call one of its static methods. Reflection provides the mechanism to achieve this dynamic behavior. This guide demonstrates how to use reflection to retrieve a class reference from its string name and subsequently invoke a static method.
Using Type.GetType for Class Retrieval
The Type.GetType
method is the key to accessing the class dynamically. It takes the fully qualified class name as a string and returns a Type
object representing that class:
<code class="language-csharp">Type classType = Type.GetType("MyClass"); </code>
Method Invocation Using Reflection
Once you have the Type
object, you can use GetMethod
to obtain a MethodInfo
object representing the static method you wish to invoke:
<code class="language-csharp">MethodInfo methodInfo = classType.GetMethod("MyStaticMethod", BindingFlags.Static | BindingFlags.Public);</code>
This retrieves the method named "MyStaticMethod," ensuring it's a public static method. The BindingFlags
specify the search criteria.
Finally, invoke the method using Invoke
:
<code class="language-csharp">methodInfo.Invoke(null, null); // null for static method, null for no parameters</code>
For methods with parameters, pass an array of objects as the second argument to Invoke
.
Important Considerations:
try-catch
blocks to handle potential exceptions (e.g., TypeLoadException
, MethodNotFoundException
).BindingFlags
accordingly.By employing these techniques, you can unlock the power of dynamic method invocation in C#, enabling flexible and adaptable applications.
The above is the detailed content of How Can I Use Reflection in C# to Invoke a Static Method on a Class Given Its Name as a String?. For more information, please follow other related articles on the PHP Chinese website!