Problem with the Vb.Net delegation?

Hi, newbie vb.net. This question can be a very newbie and answer earlier, but I could not find. I tried using lambda functions and was amazed 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 the Expected Expression. in the line DoIt = sub (s) console.WriteLine (s) . And when I changed it to DoIt = function (s) console.WriteLine (s), I got Expression does not cause a value. . What is the problem?

+4
source share
1 answer

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

The problem is that on the one hand you need to make your lambda expression in Function , not Sub , and on the other hand Console.WriteLine has no return value. The solution is to wrap this in 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 this function in your lambda expression:

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

Source: https://habr.com/ru/post/1309082/


All Articles