Vb.Net动作委托有问题吗? [英] Vb.Net action delegate problem?
问题描述
是vb.net新手。这个问题可能是新手,以前曾回答过,但我找不到。我正在尝试使用lambda功能,并在这里碰到了。
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
我在预期的表达式上获得了 DoIt = sub(s)控制台。WriteLine(s)。当我将其更改为DoIt = function(s)console.WriteLine(s)时,我得到 Expression不会产生值。错误。是什么问题?
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?
推荐答案
如果使用的是Visual Studio 2008(VB.NET 9),则VB中存在限制。 NET要求lambda表达式返回一个值,因此您不能使用 Sub
。这在VB.NET 10中已更改,因此在那种环境下,您的代码应该可以按预期工作。
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.
问题是,一方面需要将lambda表达式转换为功能
,而不是 Sub
,而另一方面, Console.WriteLine
没有返回值。解决方案是将其包装到一个调用 Console.WriteLine
且返回值的函数中:
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
然后您可以在lambda表达式中使用该函数:
Then you can use that function in your lambda expression:
Dim DoIt As Action(Of String)
DoIt = Function(s) ConsoleWriteLine(s)
这篇关于Vb.Net动作委托有问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!