什么一定要当一个普通的委托参数提供一个lambda前pressi

什么一定要当一个普通的委托参数提供一个lambda前pressi

本文介绍了为什么一定要当一个普通的委托参数提供一个lambda前pression定投的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

取方法System.Windows.Forms.Control.Invoke(代表法)

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

然而,这工作得很好:

Yet this works fine:

string str = "woop";
Invoke((Action)(() => this.Text = str));

在该方法需要一个普通的代表?

When the method expects a plain Delegate?

推荐答案

一个拉姆达前pression既可以转换为委托类型或一个前pression树 - 但它必须知道的的委托类型。只要知道签名是不够的。举例来说,假设我有:

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 动作最容易做的事情是添加扩展的方法来控制:

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前pression定投的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 06:40