【问题标题】:Embedded C# lambda expression as function parameter嵌入式 C# lambda 表达式作为函数参数
【发布时间】:2015-03-13 08:33:04
【问题描述】:

有人知道下面这段代码有什么问题,在VS2013中无法编译吗?

GenericCommand.AddHandlerFactory("MyKey", (cmd, action) =>
{
  return (command) =>
  {
    var result = new SuccessResult() { ResultText = "some example text" };
    result.Send(command.Configuration);
  };
});

AddHandlerFactory的原型是:

public static void AddHandlerFactory(string key, Func<GenericCommand, Action> handlerFactory)

VS2013编译时显示

不能在此范围内声明名为 command 的局部变量 因为它会给命令赋予不同的含义...... ....

和

委托 System.Func WindowsPhoneTestFramework.Client.AutomationClient.Remote.GenericCommand, System.Action 不接受 2 个参数

源代码的更多细节在: https://github.com/Expensify/WindowsPhoneTestFramework/blob/master/Client/AutomationClient/Remote/GenericCommand.cs

EDIT1 将第一个命令重命名为cmd,第一个错误消息就解决了。但它仍然无法编译。

错误信息是:

无法将 lambda 表达式转换为委托类型 Delegate 系统函数 WindowsPhoneTestFramework.Client.AutomationClient.Remote.GenericCommand, System.Action 因为块中的某些返回类型不是 隐式转换为委托返回类型。

【问题讨论】:

    标签: c# lambda windows-phone


    【解决方案1】:

    您有两个共享相同名称的参数:

    • (command, action) =&gt; 是一个带有名为 command 的参数的操作

    • return (command) =&gt; 是另一个动作,另一个参数名为 command

    所以你必须重命名两个参数名称之一。

    正如@Dirk 解释的那样,您返回Action&lt;T&gt; 而不是Action。所以你可以试试这个:

    GenericCommand.AddHandlerFactory("MyKey", (cmd, action) =>
    {
      return () =>
      {
        var result = new SuccessResult() { ResultText = "some example text" };
        result.Send(cmd.Configuration);
      };
    });
    

    【讨论】:

    • 这不是唯一的事情。 lambda 的返回值应该是一个 Action,但它是一个 Action.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多