VB.NET将函数传递给Action参数

时间:2017-11-21 14:08:18

标签: c# vb.net

我正在尝试基于我拥有的C#解决方案在VB.NET中编写一些东西。在C#解决方案中,我用以下函数调用该函数:

somefunction(s => Console.WriteLine(s)).Wait();

被调用的方法是:

public static Task somefuntion(Action<string> callback);

在VB.NET中我有

somefunction(Function(s) Console.WriteLine(s)).Wait()

Public Shared somefunction(ByRef callback As Action(Of string)) As Task

任何想法我做错了什么?

3 个答案:

答案 0 :(得分:1)

使用Sub而不是Function: somefunction(Sub(s) Console.WriteLine(s)).Wait()

答案 1 :(得分:1)

一个。在lambda中将Function(s)更改为Sub(s)

somefunction(Sub(s) Console.WriteLine(s)).Wait()

湾将Function关键字添加到somefunction方法签名:

Public Shared Function somefunction(ByRef callback As Action(Of String)) As Task

答案 2 :(得分:0)

检查官方文档

https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Module TestAction1
   Public Sub Main
      Dim messageTarget As Action(Of String) 

      If Environment.GetCommandLineArgs().Length > 1 Then
         messageTarget = AddressOf ShowWindowsMessage
      Else
         messageTarget = AddressOf Console.WriteLine
      End If
      messageTarget("Hello, World!")
   End Sub

   Private Sub ShowWindowsMessage(message As String)
      MsgBox(message)
   End Sub   
End Module