问题描述
我正在连接一个事件以使用一个 lambda,它需要在触发后自行删除.我无法通过将 lambda 内联到 += 事件(没有可用于删除事件的可访问变量)来做到这一点,所以我设置了一个 Action<object, EventArgs>
变量并将 lambda 移到那里.主要错误是它无法将 Action
转换为 EventHandler.我认为 lambda 表达式可以隐式转换为事件处理程序,为什么这不起作用?
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 可以隐式转换为具有正确形状的委托类型,但是两个形状相同的委托类型不能隐式转换为彼此.只需将局部变量设为 EventHandler 类型即可.
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;
(如果有帮助的话:
Action<object, EventArgs> a = (o, ea) => { };
EventHandler e = a; // not allowed
EventHandler e2 = (o,ea) => a(o,ea); // ok
)
这篇关于动作<对象,EventArgs>无法转换为 EventHandler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!