无法将 lambda 表达式转换为类型 'Delegate',因为它不是委托类型

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

我在使用 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 表达式,它不能自动将表达式转换为类似 new Delegate() 的东西,因为 Delegate 没有 public 构造函数。使用

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

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

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