简体   繁体   English

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

[英]Reflection: Invoke method, passing a delegate as parameter

I have an interface implemented in Host class that looks like this: 我在Host类中实现了一个如下所示的接口:

void Method1(Action<Args1> action1, Action<Args1> action2);

and then I have the following methods to be passed for action1 and action2 . 然后我将为action1action2传递以下方法。

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

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

Using reflection, how do I invoke it with and pass methods Action1 and Action2 ? 使用反射,我怎么跟调用它,并通过方法Action1Action2

//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 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM