lambda 表达式是一个没有名称的函数或子例程。 在任何适用委托类型的地方,都可以使用 lambda 表达式。
创建单行 Lambda 表达式函数
在可以使用委托类型的任何情况下,键入关键字
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 表达式子例程
在可以使用委托类型的任何情况下,键入关键字
Sub,如以下示例所示。Dim add1 =Sub在括号中,紧跟在
Sub之后,输入子例程的参数。 请注意,您未在Sub后面指定名称。Dim add1 = Sub(msg As String)在参数列表之后,键入单个语句作为子例程的正文。
Dim writeMessage = Sub(msg As String) Console.WriteLine(msg)通过传入字符串参数来调用 lambda 表达式。
' The following line prints "Hello". writeMessage("Hello")
要创建一个多行的 lambda 表达式函数
在可以使用委托类型的任何情况下,键入关键字
Function,如以下示例所示。Dim add1 =Function在括号中,直接在
Function后面键入函数的参数。 请注意,您未在Function后面指定名称。Dim add1 = Function(index As Integer)按 Enter。
End Function语句会自动进行添加。在函数正文中,添加以下代码以创建表达式并返回值。 不使用
As子句来指定返回类型。Dim getSortColumn = 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通过传入整数参数来调用 lambda 表达式。
Dim sortColumn = getSortColumn(0)
创建多行 Lambda 表达式子例程
在可以使用委托类型的任何情况下,键入关键字
Sub,如以下示例所示:Dim add1 =Sub在括号中,紧跟在
Sub之后,输入子例程的参数。 请注意,您未在Sub后面指定名称。Dim add1 = Sub(msg As String)按 Enter。
End Sub语句会自动进行添加。在函数正文中,添加在调用子例程时要执行的以下代码。
Dim writeToLog = Sub(msg As String) Dim log As New EventLog() log.Source = "Application" log.WriteEntry(msg) log.Close() End Sub通过传入字符串参数来调用 lambda 表达式。
writeToLog("Application started.")
示例:
lambda 表达式的常见用途是定义一个函数,该函数可以作为其类型为 Delegate的参数的参数传入。 在以下示例中,该方法 GetProcesses 返回在本地计算机上运行的进程数组。
Where类中的Enumerable方法需要Boolean委托作为其参数。 示例中的 lambda 表达式用于该目的。 它为每个只有一个线程的进程返回 True ,并在其中 filteredList选择这些线程。
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