动作<对象,EventArgs的>不能被强制转换为事件处理程序? [英] Action<object, EventArgs> could not be casted to EventHandler?

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

问题描述

我是连接最多的事件要使用的需要触发后,除去本身的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

这篇关于动作&LT;对象,EventArgs的&GT;不能被强制转换为事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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