加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 无法将lambda表达式转换为“委托”类型,因为它不是委托类

发布时间:2020-12-15 18:28:54 所属栏目:百科 来源:网络整理
导读:我在C#中遇到匿名委托lambda时遇到问题.我刚刚将应用程序转换为C#5,代表们对我一切都失控了.任何帮助都会很棒.具体错误是: Cannot convert lambda expression to type ‘Delegate’ because it is not a delegate type public void UpdateUserList(){ if (!
我在C#中遇到匿名委托lambda时遇到问题.我刚刚将应用程序转换为C#5,代表们对我一切都失控了.任何帮助都会很棒.具体错误是:

Cannot convert lambda expression to type ‘Delegate’ because it is not
a delegate type

public void UpdateUserList()
{
  if (!Monitor.TryEnter((object)this.LvPerson,150))
      return;

  if (this.InvokeRequired)
  {
      this.Invoke((Delegate) (() => this.UpdateUserList()));              
  }
  else
  { ... }
}

我也试过了

this.Invoke(() => {this.UpdateUserList();});

在将项目从Visual Studio 2008移动到Visual Studio 2015之前,我不确定问题出在哪里.

再次感谢您的帮助!

解决方法

Invoke方法需要一个Delegate类型实例,因为你使用lambda表达式它不能自动将表达式转换为类似新的Delegate(),因为Delegate没有公共构造函数.运用
this.Invoke(new Action(() => {this.UpdateUserList();}));

应该解决问题,因为Action是Delegate的子类.要在使用Invoke时摆脱冗余的新Action(…),你可以编写一组扩展方法,将Action作为参数,这样新的Action(…)将由C#编译器处理,所以你每次使代码更清洁时都不必写它.

如果您正在使用Invoke进行某些可能涉及其他线程的异步操作,请查看任务并行库(TPL)和基于任务的异步模式(TAP),后者内置了对C#和Visual Basic.NET的支持,使用await将不再需要调用Invoke()并允许您在后台运行某些操作来释放UI.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读