Why must a lambda expression be cast when supplied as a plain Delegate parameter(当作为普通委托参数提供时,为什么必须强制转换 lambda 表达式)
问题描述
取方法System.Windows.Forms.Control.Invoke(Delegate方法)
Take the method System.Windows.Forms.Control.Invoke(Delegate method)
为什么会出现编译时错误:
Why does this give a compile time error:
string str = "woop";
Invoke(() => this.Text = str);
// Error: Cannot convert lambda expression to type 'System.Delegate'
// because it is not a delegate type
但这工作正常:
string str = "woop";
Invoke((Action)(() => this.Text = str));
什么时候方法需要一个普通的委托?
When the method expects a plain Delegate?
推荐答案
lambda 表达式可以转换为委托类型或表达式树 - 但它必须知道哪个委托类型.仅仅知道签名是不够的.例如,假设我有:
A lambda expression can either be converted to a delegate type or an expression tree - but it has to know which delegate type. Just knowing the signature isn't enough. For instance, suppose I have:
public delegate void Action1();
public delegate void Action2();
...
Delegate x = () => Console.WriteLine("hi");
您希望 x
引用的对象的具体类型是什么?是的,编译器可以生成具有适当签名的新委托类型,但这很少有用,而且您最终检查错误的机会更少.
What would you expect the concrete type of the object referred to by x
to be? Yes, the compiler could generate a new delegate type with an appropriate signature, but that's rarely useful and you end up with less opportunity for error checking.
如果你想让 Control.Invoke
使用 Action
更容易调用,最简单的方法是向 Control 添加扩展方法:
If you want to make it easy to call Control.Invoke
with an Action
the easiest thing to do is add an extension method to Control:
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate) action);
}
这篇关于当作为普通委托参数提供时,为什么必须强制转换 lambda 表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当作为普通委托参数提供时,为什么必须强制转换 lambda 表达式


基础教程推荐
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01