C#--无法将lambda表达式转换为类型‘Delegate’,原因是它不是委托类型

报错如下:

 

主要是为了在子线程中更新UI线程

 对于Control.Invoke()来说,任何的代理类型都是可接受的,也就是说ThreadStart和MethodInvoker都是可以接受的类型。这样编译器反而不知道应该用哪个代理去匹配匿名函数了,导致了编译错误的发生。
知道了原因,问题就很容易解决了。我们只需要加上MethodInvoker这个wrapper就能使用匿名函数了。

this.label7.Invoke(new MethodInvoker(delegate { this.label7.Text = msg.strMsg; }));

或者用lamada表达式:
this.label7.Invoke(new MethodInvoker(() => this.label7.Text = msg.strMsg));

 

// 以下为委托的几种写法

             1、 this.Invoke( (MethodInvoker)(()=> { …方法体…}));

             2、 this.Invoke( (MethodInvoker) delegate{…方法体…});

             3、this.Invoke( new MethodInvoker (()=> { …方法体…}));

             4、 this.Invoke( new MethodInvoker (delegate{…方法体…}));

posted @ 2021-01-02 13:28  包子789654  阅读(4055)  评论(2编辑  收藏  举报