当作为纯Delegate参数提供时,为什么必须强制转换lambda表达式

采取方法System.Windows.Forms.Control.Invoke(Delegate方法)


为什么会给出编译时错误:


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));

该方法何时需要普通代表?


冉冉说
浏览 475回答 3
3回答

月关宝盒

Lambda表达式可以转换为委托类型或表达式树-但是必须知道哪种委托类型。仅知道签名是不够的。例如,假设我有:public delegate void Action1();public delegate void Action2();...Delegate x = () => Console.WriteLine("hi");您期望所指对象的具体类型x是什么?是的,编译器可以生成带有适当签名的新委托类型,但这很少有用,并且您进行错误检查的机会也会减少。如果你想很容易地调用Control.Invoke与Action最容易做的事情是添加扩展的方法来控制:public static void Invoke(this Control control, Action action){    control.Invoke((Delegate) action);}

墨色风雨

厌倦了一遍又一遍地铸造lambda?public sealed class Lambda<T>{&nbsp; &nbsp; public static Func<T, T> Cast = x => x;}public class Example{&nbsp; &nbsp; public void Run()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // Declare&nbsp; &nbsp; &nbsp; &nbsp; var c = Lambda<Func<int, string>>.Cast;&nbsp; &nbsp; &nbsp; &nbsp; // Use&nbsp; &nbsp; &nbsp; &nbsp; var f1 = c(x => x.ToString());&nbsp; &nbsp; &nbsp; &nbsp; var f2 = c(x => "Hello!");&nbsp; &nbsp; &nbsp; &nbsp; var f3 = c(x => (x + x).ToString());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP