【问题标题】:How to pass System.Action parameter with lambda expressions for ForEach?如何使用 ForEach 的 lambda 表达式传递 System.Action 参数?
【发布时间】:2017-01-19 16:40:28
【问题描述】:

当尝试使用 lambda 表达式而不是 AddressOf 运算符时,带有 ForEach sub 的参数时,我收到以下错误:

语句 lambda 不能转换为表达式树

这是AddressOf 代码,有效:

lista.ForEach(new Action(Of String)(AddressOf Console.WriteLine))

这是产生错误的 lambda 代码:

lista.ForEach(new Action(Of String)(Function(x) x = "teste")

正在调用方法ForEach,因此需要将Action 作为参数传递。

谁能帮助我或告诉我这是否可能?

【问题讨论】:

  • lista.ForEach(new Action(Of String)(Sub(x) x = "teste")
  • 谢谢法比奥,但我得到了同样的编译错误。 “语句 lambda...”
  • 下一行将编译成功 -> lista.ForEach(new Action(Of String)(Sub(value) Console.WriteLine(value)))。所以你甚至可以删除 new Action... 并在那里传递 lambda:lista.ForEach(Sub(value) Console.WriteLine(value))
  • lista的类型是什么?
  • 当我使用Console.WriteLine(variable) 时,它工作得很好,我已经能够这样使用它了。但是,当我尝试使用 variable = "teste" 之类的变量执行某些过程时,我得到了错误。 listaList<string> 类型:TypeSystem.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

标签: vb.net lambda foreach compiler-errors uipath


【解决方案1】:

最终,你的问题是这样的:

lista.ForEach(new Action(Of String)(Function(x) x = "teste")

ForEach 是一个不作为操作结果返回值的方法。

改成:

lista.ForEach(new Action(Of String)(Sub(x) x = "teste"))

虽然,我根本不喜欢那个方法签名,但你需要执行的这个动作过于复杂了。

考虑到 ForEach 方法 (MSDN) 接受 Action<T>,则无需声明 new Action(of String)。您只需要关注您希望传递给 List/Array 以对每个元素执行的 Lambda Express

阅读以了解基础知识VB's Lambda Expression Implementation

有了这个,试试这个模式吧:

lista.ForEach(Sub(x) x = "teste")

lista.ForEach(Function(x) x = "teste")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多