通过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!