反射:调用方法,将委托作为参数传递

sjl*_*wis 2 c# reflection

我有一个在Host类中实现的接口,如下所示:

void Method1(Action<Args1> action1, Action<Args1> action2);
Run Code Online (Sandbox Code Playgroud)

然后我有以下方法传递action1action2.

private void Action1(Args1 obj)
{
//...
}

private void Action2(Args1 obj)
{
//...
}
Run Code Online (Sandbox Code Playgroud)

使用反射,我如何调用它并传递方法Action1Action2

And*_*tan 5

//here you pass the methods Action1 and Action2 as parameters
//to the delegates - if you need to construct these by reflection
//then you need to reflect the methods and use the
//Delegate.CreateDelegate method.
var param1 = new Action<Args1>(Action1);
var param2 = new Action<Args1>(Action2);
//instance of Host on which to execute
var hostInstance = new Host();
var method = typeof(Host).GetMethod("Method1", 
  BindingFlags.Public | BindingFlags.Instance);

method.Invoke(hostInstance, new object[] { param1, param2 });
Run Code Online (Sandbox Code Playgroud)