HOW TO:建立 Lambda 運算式
更新:2007 年 11 月
「Lambda 運算式」(Lambda Expression) 是沒有名稱的函式,會計算單一運算式並傳回其值。
若要建立 Lambda 運算式
在可以使用委派型別 (Delegate Type) 的方法中,輸入關鍵字 Function,如下列範例所示:
Dim add1 = Function
緊接著 Function 之後,於括號中輸入函式的參數。請注意,不要在 Function 之後指定名稱。
Dim add1 = Function (num As Integer)
在參數清單之後,輸入單一運算式做為函式主體。運算式計算的值是函式傳回的值。您不能使用 As 子句指定傳回型別。
Dim add1 = Function(num As Integer) num + 1
您可以藉由傳遞整數引數來呼叫 Lambda 運算式。
' The following line prints 6. Console.WriteLine(add1(5))
或者,也可以透過下列範例來達到相同的結果:
Console.WriteLine((Function(num As Integer) num + 1)(5))
範例
Lambda 運算式的一般用途是定義函式,該函式可以傳遞為參數的引數,其型別為 Delegate。在下列範例中,GetProcesses 方法會傳回本機電腦上執行之處理序的陣列。Enumerable 類別 (Class) 的 Where 方法需要 Boolean 委派做為其引數。範例中的 Lambda 運算式便是以此目的而傳送。它會針對只有一個執行緒的各個處理序以及在 filteredQuery 中選取的處理序傳回 True。
Sub Main()
' Create an array of running processes.
Dim procList As Process() = Diagnostics.Process.GetProcesses
' Return the processes that have one thread. Notice that the type
' of the parameter does not have to be explicitly stated.
Dim filteredList = procList.Where(Function(p) p.Threads.Count = 1)
' Display the name of each selected process.
For Each proc In filteredList
MsgBox(proc.ProcessName)
Next
End Sub
上述範例相當於使用 Language-Integrated Query (LINQ) 語法撰寫的下列程式碼:
Sub Main()
Dim filteredQuery = From proc In Diagnostics.Process.GetProcesses _
Where proc.Threads.Count = 1 _
Select proc
For Each proc In filteredQuery
MsgBox(proc.ProcessName)
Next
End Sub
請參閱
工作
HOW TO:在 Visual Basic 中將程序傳遞至其他程序