问题描述
我知道可以通过反射轻松订阅事件的方法,但是现在我想知道是否有一种方法可以对委托进行相同的操作。基本上,我需要使用Reflection调用委托的'+ ='运算符。这是一个代码段:
using System;
class Foo
{
public event Action Action1;
public Action Action2;
public void Call()
{
Action1?.Invoke();
Action2?.Invoke();
}
}
class Program
{
static void Main()
{
var foo = new Foo();
// Subscribing to the event Action1
var eventInfo = typeof(Foo).GetEvent("Action1");
Action tmp = () => { Console.WriteLine("Hello"); };
var args = new object[] { tmp };
eventInfo.AddMethod?.Invoke(foo,args);
// Subscribing to the delegate Action2 with the += operator.
// How can I do this with Reflection,instead ???
foo.Action2 += () => { Console.WriteLine("Bye"); };
foo.Call();
}
}
Output:
Hello
Bye
我需要使用反射来订阅Action2(例如,如果Action2是私有方法)。有什么想法可以实现吗?预先感谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)