嵌入式 C# lambda 表达式作为函数参数

Embedded C# lambda expression as function parameter

有谁知道下面这段代码有什么问题,无法在 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编译时显示

A local variable named command cannot be declared in this scope because it would give a different meaning to command .... ....

Delegate System.Func WindowsPhoneTestFramework.Client.AutomationClient.Remote.GenericCommand, System.Action does not take 2 arguments

源代码的更多详细信息位于: https://github.com/Expensify/WindowsPhoneTestFramework/blob/master/Client/AutomationClient/Remote/GenericCommand.cs

EDIT1 将第一个命令重命名为 cmd,第一个错误消息已解决。但是还是编译不了。

错误消息是:

cannot convert lambda expression to delegate type Delegate System.Func WindowsPhoneTestFramework.Client.AutomationClient.Remote.GenericCommand, System.Action because some of the return types in the block are not implicitly convertible to the delegate return type.

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

  • (command, action) => 是一个参数名为 command

  • 的动作
  • return (command) => 是另一个动作,另一个参数命名为 command

因此您必须重命名两个参数名称之一。

正如@Dirk 解释的那样,你 return 一个 Action<T> 而不是 Action。所以你可以试试这个:

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