繁体   English   中英

嵌入式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中编译时,它显示

不能在此范围内声明名为command的局部变量,因为它将赋予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,解决第一个错误msg。 但是它仍然不能编译。

错误消息为:

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

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

  • (command, action) =>是带有参数命名command一项操作

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

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

正如@Dirk解释的那样,您返回Action<T>而不是Action 因此,您可以尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM