动作<对象,EventArgs>无法转换为EventHandler? [英] Action<object, EventArgs> could not be cast to EventHandler?

查看:148
本文介绍了动作<对象,EventArgs>无法转换为EventHandler?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在整理一个使用lambda的事件,该事件需要在触发后自行删除。我无法通过将lambda内联到+ =事件(没有可用于删除事件的可访问变量)来做到这一点,所以我设置了 Action< object,EventArgs> 变量并将lambda移到那里。主要错误是它无法将 Action< object,EventArgs> 转换为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可以隐式转换为委托类型具有正确的形状,但是两个相同形状的委托类型不能隐式地相互转换。

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

这篇关于动作&lt;对象,EventArgs&gt;无法转换为EventHandler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆