使用C#中的名称调用方法

Chr*_*ris 17 c# reflection methods

我的应用程序中有许多"作业",每个作业都有一个需要调用的方法列表及其参数.基本上称为包含以下对象的列表:

string Name;
List<object> Parameters;
Run Code Online (Sandbox Code Playgroud)

所以基本上,当一个作业运行时,我想通过这个列表枚举,并调用相关的方法.例如,如果我有如下方法:

TestMethod(string param1, int param2)
Run Code Online (Sandbox Code Playgroud)

我的方法对象是这样的:

Name = TestMethod
Parameters = "astring", 3
Run Code Online (Sandbox Code Playgroud)

是否有可能做到这一点?我想反射将成为关键.

Igb*_*man 41

当然,你可以这样做:

public class Test
{
    public void Hello(string s) { Console.WriteLine("hello " + s); }
}

...

{
     Test t = new Test();
     typeof(Test).GetMethod("Hello").Invoke(t, new[] { "world" }); 

     // alternative if you don't know the type of the object:
     t.GetType().GetMethod("Hello").Invoke(t, new[] { "world" }); 
}
Run Code Online (Sandbox Code Playgroud)

Invoke()的第二个参数是一个Object数组,其中包含要传递给方法的所有参数.

假设这些方法都属于同一个类,那么你可以使用类的方法:

public void InvokeMethod(string methodName, List<object> args)
{
    GetType().GetMethod(methodName).Invoke(this, args.ToArray());
}
Run Code Online (Sandbox Code Playgroud)