How to invoke a method using C# reflection?
The steps for invoking a method through C# reflection are as follows:
- Include the System.Reflection namespace.
- Use the Type.GetType method to obtain the Type object of the class in which the method is to be called.
- You can use the Type.GetMethod method to retrieve the MethodInfo object of the method to be called. This can be done by providing information such as the method name and parameter types.
- Use the MethodInfo.Invoke method to call a method. Pass in the instance object to be called (if it is an instance method) and the method’s parameters (if there are any).
Here is an example code demonstrating how to invoke a method using C# reflection.
using System;
using System.Reflection;
public class MyClass
{
public void MyMethod(string message)
{
Console.WriteLine("MyMethod: " + message);
}
}
class Program
{
static void Main()
{
// 获取MyClass类的Type对象
Type type = typeof(MyClass);
// 获取MyMethod方法的MethodInfo对象
MethodInfo method = type.GetMethod("MyMethod");
// 创建MyClass的实例
MyClass myObject = new MyClass();
// 调用MyMethod方法
method.Invoke(myObject, new object[] { "Hello World!" });
}
}
When running the code above, the output will be:
MyMethod: Hello World!
Note: If the method you want to call is a static method, you can pass in null as the instance object. If the method is private, you can use the BindingFlags.NonPublic flag to obtain the MethodInfo object of the method.