我想在运行时连接一个通用委托,您可以查看下面的示例代码。
但是,在将委托绑定到事件时,Delegate.CreateInstance
我得到一个ArgumentException
('错误绑定到目标方法')。
class MyClass
{
public event EventHandler<MyEventArgs> OnRequest;
}
class MyEventArgs : EventArgs { }
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
EventInfo eventInfo = obj.GetType().GetEvent("OnRequest");
Type delegateType = eventInfo.EventHandlerType;
MethodInfo methodInfo = typeof(Program).GetMethod("OnRequestReceived");
Delegate del = Delegate.CreateDelegate(delegateType, methodInfo);
}
public static void OnRequestReceived(object o, EventArgs e) { }
}