温馨提示×

通过MethodInfo调用方法

小云
119
2023-09-27 05:42:26
栏目: 编程语言

要通过MethodInfo调用方法,首先需要获取MethodInfo实例,然后使用Invoke方法来调用该方法。

以下是一个示例代码:

using System;
using System.Reflection;
public class MyClass
{
public void MyMethod(string message)
{
Console.WriteLine("MyMethod is called with message: " + message);
}
}
public class Program
{
public static void Main()
{
// 获取MyMethod的MethodInfo实例
Type type = typeof(MyClass);
MethodInfo methodInfo = type.GetMethod("MyMethod");
// 创建MyClass的实例
MyClass myClass = new MyClass();
// 调用MyMethod方法
methodInfo.Invoke(myClass, new object[] { "Hello, World!" });
}
}

在上面的示例中,我们首先使用typeof运算符获取MyClass的Type,然后使用GetMethod方法获取MyMethod的MethodInfo实例。接下来,我们创建了MyClass的实例myClass,并使用Invoke方法调用MyMethod方法。通过传递一个string类型的参数数组来提供方法的参数。

运行以上代码,将会在控制台输出:

MyMethod is called with message: Hello, World!

0