c# - 反射:调用方法,传递委托(delegate)作为参数

标签 c# reflection

我在 Host 类中实现了一个接口(interface),如下所示:

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

然后我为 action1action2 传递以下方法。

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

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

使用反射,如何使用并传递方法 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 });

关于c# - 反射:调用方法,传递委托(delegate)作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7904656/

相关文章:

c# - 特定条目的 LINQ 索引

c# - Entity Framework 中 Select 和 Where 之间的区别

java - 从实现类中获取类型参数的类

c# - Getfield.SetValue 不起作用

c# - 有没有办法列出 .Net 程序集中方法的所有调用和硬编码字符串参数?

C# 计时器 (TimeSpan) 在后台持续滴答作响(if 语句在不为 true 时适用)

c# - 我可以在没有定时器组件的情况下使用定时器吗?

c# - C# 程序输出目录中的公共(public)文件

java - 确定通用类型字段的类类型

java - 使用 java 反射将派生对象传递到需要父类(super class)的方法中?