反编译的 DLL - CS1660 无法转换为 'Delegate' 因为类型不是委托类型

Decompiled DLL - CS1660 Cannot convert to 'Delegate' because type is not of delegate type

我用 dotpeek 反编译了一个 .net 4.6.1 项目 dll。反编译后出现以下错误:

CS1660 无法转换为 'Delegate' 因为类型不是委托类型

private void MainLogAdd(string s, System.Drawing.Color color)
    {
      this.logcol.Add(color);
      this.lstLogBox.Invoke((delegate) (() =>
      {
        this.lstLogBox.Items.Add((object) ("[" + DateTime.Now.TimeOfDay.ToString().Substring(0, 8) + "] " + s));
        this.lstLogBox.TopIndex = this.lstLogBox.Items.Count - 1;
      }));
    }

使用新操作更改后 'Action 1 does not contain a constructor that takes its arguments'

(delegate)替换为new System.Action:

    this.lstLogBox.Invoke(new System.Action(() =>
    {
        this.lstLogBox.Items.Add((object) ("[" + DateTime.Now.TimeOfDay.ToString().Substring(0, 8) + "] " + s));
        this.lstLogBox.TopIndex = this.lstLogBox.Items.Count - 1;
    }));

Invoke 方法接受类型 Delegate 的参数,它是一个抽象 class 和所有委托的基类型。

Lambda 表达式可以编译为表达式树 (Expression<Func<...>>) 或普通委托(ActionFunc)。 C# 编译器需要知道委托的确切类型,因此它可以生成 lambda 表达式的代码。

顺便说一下,这是大多数 C# 反编译器的问题。 ILSpy 是我的好运气。

传递给 .Invoke() 的值需要是实际实例化的委托类型,例如 Action,因为 Windows Forms 库是在 C# 中存在 lambda 之前创建的。而不是像反编译器写的那样将 lambda 转换为 delegate,它应该是这样的:

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

我相信只要将 (delegate) 改为 (Action) 就可以了

之前:

this.lstLogBox.Invoke((delegate) (() =>

之后:

this.lstLogBox.Invoke((Action) (() =>

这是一个例子:

编辑

您说您已经有一个名为 Action 的 class,它导致了冲突。您可以使用全名:

this.lstLogBox.Invoke((System.Action) (() =>

或者您可以创建一个别名,例如将其放在 class:

的顶部
using SystemAction = System.Action;

然后使用别名..

this.lstLogBox.Invoke((SystemAction) (() =>

或者您可以重命名您的 class :)