动作<对象,EventArgs的>不能被强制转换为事件处理程序?转换为、对象、动作、事件

2023-09-04 01:44:56 作者:朕今晚翻你牌子

我是连接最多的事件要使用的需要触发后,除去本身的lambda。通过内联拉姆达到+ =事件中,我不能这样做(没有accessable变量用来删除事件),所以我成立了一个动作<对象,EventArgs的> 变量和感动拉姆达那里。主要错误是,它不能转换的动作<对象,EventArgs的> 到事件处理程序。我认为拉姆达EX pressions是隐含可转换到事件处理程序,为什么不这项工作?

I was wiring up an event to use a lambda which needed to remove itself after triggering. I couldn't do it by inlining the lambda to the += event (no accessable variable to use to remove the event) so i set up an Action<object, EventArgs> variable and moved the lambda there. The main error was that it could not convert an Action<object, EventArgs> to an EventHandler. I thought lambda expressions were implicitly convertable to event handlers, why doesn't this work?

推荐答案

lambda表达式是隐式转换为用正确的形状委托类型,但有两个相同形状的委托类型不能隐式转换到另一个。只要局部变量的类型为事件处理程序来代替。

Lambdas are implicitly convertible to delegate types with the right shape, but two same-shaped delegate types are not implicitly convertible to one another. Just make the local variable have type EventHandler instead.

EventHandler h = (o, ea) => { ... };
e += h;
...
e -= h;

(在情况下,它可以帮助

(in case it helps:

Action<object, EventArgs> a = (o, ea) => { }; 
EventHandler e = a;  // not allowed
EventHandler e2 = (o,ea) => a(o,ea);  // ok