此代码段无法编译。如何正确使用lambda函数?
我尝试在各个地方向函数发送整数。它没有返回正确的值。
我希望DoSomething例程为并行任务应用程序选择各种可能的子任务。
我一直在尝试遵循设置任务的示例:
Dim action As Action(Of Object)
action = Sub(obj As Object)
MessageBox.Show("Task manager " + vbCrLf +
"Current ID " + Task.CurrentId.ToString + vbCrLf + "Object " + obj.ToString + vbCrLf + "Thread ID " + Thread.CurrentThread.ManagedThreadId.ToString)
End Sub
Dim t1 As New Task(action, "Control 1")
Dim t3 As New Task(action, "Control 2")
Dim t4 As New Task(action, "Control 3")
t1.Start()
t1.Wait()
t3.Start()
t3.Wait()
t4.Start()
t4.Wait()
Dim t As Task = Task.Factory.StartNew(action, "Control 4")
Dim t5 = Function(ctr As Integer) ctr + 2
MessageBox.Show("Answer " + t5(6).ToString)
这些工作,但是进行函数调用的最后一次尝试失败了。
Dim DoSomething As Action(Of Integer)
DoSomething = Function(index As Integer)
Select Case index
Case 0
Return "FirstName"
Case 1
Return "LastName"
Case 2
Return "CompanyName"
Case Else
Return "LastName"
End Select
End Function
If DoSomething(1).ToString = "FirstName" Then
MessageBox.Show("Hello world")
End If
我希望case语句中有一个匹配项,但是返回值不存在,“函数不返回值”或返回子例程调用的路径。
答案 0 :(得分:1)
如果您希望DoSomething返回一个String
值,则必须将其定义为一个Func(Of Integer, String)
。作为Action(Of Integer)
,它被视为子例程。
Dim DoSomething As Func(Of Integer, String)
DoSomething = Function(index As Integer)
Select Case index
Case 0
Return "FirstName"
Case 1
Return "LastName"
Case 2
Return "CompanyName"
Case Else
Return "LastName"
End Select
End Function
请注意,它不会显示“ Hello World”消息框,因为传递1将产生“ LastName”。
如果DoSomething的值从不打算返回字符串并且应该真正是Action(Integer),则这更适合写DoSomething的值:
Dim DoSomethingAsAction As Action(Of Integer)
DoSomethingAsAction = Sub(index As Integer)
Select Case index
Case 0
MsgBox("Hello World!")
End Select
End Sub
DoSomethingAsAction.Invoke(0)