【问题标题】:Convert lambda to custom delegate将 lambda 转换为自定义委托
【发布时间】:2013-09-03 12:33:02
【问题描述】:

在程序集MyLibrary.Common 中,我定义了一个通用委托类型:

namespace MyLibrary.Common {
  public delegate TResult Instruction<in TArgument, out TResult>(
      CancellationToken cancellationToken,
      Action reportProgress,
      TArgument argument);
}

然后我通过链接到相应的 DLL 在另一个 VS2010 项目中引用这个程序集。

当我想使用以下方法创建此类型的实例时,我收到以下错误:

Instruction<string, bool> instruction =
  (cancellationToken, reportProgress, argument) => SomeOperation(argument);

private static bool SomeOperation(string arg) {
  return false;
}

错误我在instruction = ...线上得到的是

无法将源类型“lambda 表达式”转换为目标类型“MyLibrary.Common.Instruction”


当我尝试将SomeOperation(argument) 的应用程序编写为private static bool SomeOperationWrapped(string argument) 并将SomeOperationWrapped 标识符分配给我的instruction 变量时,我得到的错误是

期望一个带有 '??? 的方法SomeOperationWrapped()' 签名


奇怪的是,在另一个 VS2010 项目中,将 lambda 表达式分配给我的 Instruction&lt;TArgument, TResult 变量时没有遇到任何问题。

【问题讨论】:

  • 奇怪,对我来说效果很好。
  • 您是否尝试过将匿名委托转换为所需的类型: Instruction instruction = (Instruction)((cancellationToken, reportProgress, argument) => SomeOperation(argument) );
  • 试试Instruction&lt;string, bool&gt; instruction = new Instruction&lt;string, bool&gt;((cancellationToken, reportProgress, argument) =&gt; SomeOperation(argument));

标签: c# delegates implicit-conversion implicit-typing


【解决方案1】:

有趣的是,您说在不同的 VS2010 项目中没有此类问题。看看那个代码(有效)是什么样子会很好。

源项目和消费项目是否都设置为针对相同的 .Net Framework 版本并且可能还使用相同的工具版本?

也许编译器在推断类型时遇到问题 - 尝试使 lambda 参数显式类型化,和/或将 lambda 显式转换为委托类型:

Instruction<string, bool> instruction = (CancellationToken cancellationToken, Action reportProgress, string argument) => SomeOperation(argument);

Instruction<string, bool> instruction = (Instruction<string, bool>)((CancellationToken cancellationToken, Action reportProgress, string argument) => SomeOperation(argument));

【讨论】:

    【解决方案2】:

    chamila_c's answer 的启发,结果证明自己打开麻烦的项目(而不是打开它的父解决方案)可以解决问题。
    重现修复的步骤:

    • 自行打开项目。 VS2010 为其创建了一个新的(临时)解决方案。
    • 打开项目的原始解决方案以继续处理您的代码

    迄今为止,我并不确切知道为什么会这样,但我认为这是某种不合时宜的“清洁项目”操作。

    【讨论】:

    • 你确定你引用了正确的 DLL 吗?听起来您正在获得不同版本的 MyLibrary.Common。
    • 我确信我引用的 DLL 是正确的。我检查了两倍、三倍和四倍
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2010-09-08
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多