Dynamic Class Access in C# using Reflection
C# developers often encounter scenarios requiring dynamic class access based on string representations. This article demonstrates how to leverage reflection to retrieve class references from strings.
Imagine you have a string ("MyClass", for example) representing a class name, and you need to call a method within that class. Reflection provides the solution.
The core functionality relies on the Type.GetType
method. Here's an example:
<code class="language-csharp">using System; using System.Reflection; public class Example { public static void Main(string[] args) { Type type = Type.GetType("MyClass"); // Get the Type object MethodInfo method = type.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Static); // Get the method method.Invoke(null, null); // Invoke the method } } public class MyClass { public static void MyMethod() { Console.WriteLine("MyMethod called!"); } }</code>
This code uses Type.GetType
to obtain a Type
object from the string. GetMethod
then retrieves the specified static method, and Invoke
executes it.
Note that this example uses a public static method. Adjusting the BindingFlags
allows access to other method types (e.g., BindingFlags.Instance | BindingFlags.NonPublic
for private instance methods).
Understanding Type.GetType
and other reflection methods unlocks dynamic interaction with your C# classes, offering significant flexibility in your applications.
The above is the detailed content of How Can I Get C# Class References from Strings Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!