通过MethodInfo调用方法
文章标签
MethodInfo
要通过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!
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:租用VPS主机有什么优势 下一篇:租用香港云主机如何防御DDOS攻击
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。