Use C# reflection to get class reference from string
In C#, obtaining a class reference from a string requires the use of reflection mechanism. Here’s how to do it:
Use the Type.GetType method:
Type.GetType("FooClass")
: Get the Type instance corresponding to the specified string (for example, "FooClass"). Invoke()
: To call a static method, such as FooClass.MyMethod()
, you can use the Invoke()
method to call on the retrieved MethodInfo
object. Example:
<code class="language-csharp">using System; using System.Reflection; class Program { static void Main() { // 获取Type实例 Type t = Type.GetType("FooClass"); // 获取静态方法的MethodInfo MethodInfo method = t.GetMethod("MyMethod", BindingFlags.Static | BindingFlags.Public); // 调用方法 method.Invoke(null, null); } } class FooClass { public static void MyMethod() { Console.WriteLine("MyMethod invoked via reflection!"); } }</code>
This method retrieves the class reference directly from the string and calls the static method of the class.
The above is the detailed content of How Can I Retrieve a C# Class Reference from a String Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!