Vb.Net动作委托问题?

发布于 2024-08-31 20:00:32 字数 547 浏览 2 评论 0原文

我是 vb.net 新手。这个问题可能很新手,之前已经回答过,但我找不到。我正在尝试 lambda 功能并在这里受到打击。

 Private Function HigerOrderTest(highFunction as Func(Of Int16,Int16)) As Action(of String)
  Dim sam = highFunction(3)    
  Dim DoIt as Action(of String)
  DoIt = sub(s) console.WriteLine(s)            
    return DoIt  
 End Function

我在 DoIt = sub(s) console.WriteLine(s) 行得到了 “预期表达式。”。当我将其更改为 DoIt = function(s) console.WriteLine(s) 时,我得到了 Expression does not generated a value. 错误。有什么问题吗?

Am vb.net newbie. This question might be very novice and answered before, but i couldn't find. I was trying the lambda features and got struck here.

 Private Function HigerOrderTest(highFunction as Func(Of Int16,Int16)) As Action(of String)
  Dim sam = highFunction(3)    
  Dim DoIt as Action(of String)
  DoIt = sub(s) console.WriteLine(s)            
    return DoIt  
 End Function

I got "Expression expected." at line DoIt = sub(s) console.WriteLine(s). And when i changed this to DoIt = function(s) console.WriteLine(s) i got Expression does not produce a value. error. Whats the problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

别再吹冷风 2024-09-07 20:00:32

如果您使用的是 Visual Studio 2008 (VB.NET 9),则 VB.NET 中存在一个限制,要求 lambda 表达式返回一个值,因此您不能使用 Sub。这在 VB.NET 10 中发生了变化,因此在该环境中您的代码应该按预期工作。

问题在于,一方面您需要将 lambda 表达式设为 Function,而不是 Sub,而另一方面 Console.WriteLine > 没有返回值。解决方案是将其包装到一个调用 Console.WriteLine 并返回一个值的函数中:

Private Function ConsoleWriteLine(ByVal text As String) As String
    Console.WriteLine(text)
    Return text
End Function

然后您可以在 lambda 表达式中使用该函数:

Dim DoIt As Action(Of String)
DoIt = Function(s) ConsoleWriteLine(s)

If you are using Visual Studio 2008 (VB.NET 9), there is a limitation in VB.NET that requires that lambda expressions returns a value, so you cannot use Sub. This has changed in VB.NET 10, so in that environment your code should work as expected.

The problem is that on one hand you need to make your lambda expression into a Function, not a Sub, while on the other hand Console.WriteLine does not have a return value. The solution is to wrap this into a function that calls Console.WriteLine and returns a value:

Private Function ConsoleWriteLine(ByVal text As String) As String
    Console.WriteLine(text)
    Return text
End Function

Then you can use that function in your lambda expression:

Dim DoIt As Action(Of String)
DoIt = Function(s) ConsoleWriteLine(s)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文