如何在 C#2 中创建具有 3 个参数的委托方法?
我有以下方法:
private void WriteTrace(object sender, EventArgs e, EventElement eventElement)
{
/* ... */
}
当我想像这样创建委托时:
Type controlType = control.GetType();
MethodInfo method = typeof(Trace).GetMethod("WriteTrace", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
EventInfo eventInfo = type.Value.GetType().GetEvent("Load"); // for the sample, we suppose the control is a form.
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, method);
eventInfo.AddEventHandler(control, handler);
该行
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, method);
生成错误:
绑定到目标方法时出错
但我不知道为什么?
问候,
弗洛里安
I have the following method :
private void WriteTrace(object sender, EventArgs e, EventElement eventElement)
{
/* ... */
}
When I want to create Delegate like this :
Type controlType = control.GetType();
MethodInfo method = typeof(Trace).GetMethod("WriteTrace", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
EventInfo eventInfo = type.Value.GetType().GetEvent("Load"); // for the sample, we suppose the control is a form.
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, method);
eventInfo.AddEventHandler(control, handler);
The line
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, method);
generates an error :
Error binding to target method
But I don't know why ?
Regards,
Florian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Form.Load
的类型是EventHandler
,它只有两个参数,而不是三个。换句话说,这也会失败:您无法从参数数量错误的方法创建事件处理程序。 (实际上,创建像这样的开放委托有一些技巧,但它们与这里无关,IMO。)
您真正想要实现什么?在这种情况下,您期望
eventElement
是什么?请注意,您可以使用 lambda 表达式来捕获变量,例如,
这对您有帮助吗?或者您真的需要通过反思来做到这一点吗?
The type of
Form.Load
isEventHandler
, which only has two parameters, not three. In other words, this would fail too:You can't create an event handler from a method with the wrong number of parameters. (Actually there are some tricks around creating open delegates like this, but they're not relevant here, IMO.)
What are you really trying to achieve? What would you expect
eventElement
to be in this case?Note that you can use lambda expressions to capture variables, e.g.
Does that help you at all? Or do you really need to do this with reflection?
简而言之,您不能直接将事件处理程序绑定到具有三个参数的方法;您传入的方法必须与签名完全匹配。
问题是,这个“EventElement”参数从哪里来?一旦您知道了这一点,您就可以将其存储在另一个对象中,ala:
...然后绑定它...
然后 thunk 会将事件转发给您。
The short answer is you cannot directly bind the event handler to a method with three parameters; the method you pass in must match the signature exactly.
The question is, where does this "EventElement" parameter come from? Once you know that, you can squirrel it away in another object, ala:
...and then bind it...
And then the thunk will forward the event to you.