1.首先创建单行的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))
或者,也可以按下面的示例所示得到同样的结果:
- 但是对于我这样起初学习lambda表达式的人还是有点晦涩的。所以从维护和读懂的角度来看还是分开写比较好。
- 但是中国软件人员都是大多合并到一起的。所以为了读懂别人的优秀代码也只能学会这么写了。但是自己还是不会这么写的。
创建单行 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")
在任何可以使用委托类型的情况下,键入关键字 Function,如下面的示例所示。
Dim add1 = Function
按 Enter。 将自动添加 End Function 语句。
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
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 方法返回在本地计算机上运行的进程的数组。 Enumerable 类中的 Where 方法需要使用一个 Boolean 委托作为参数。 该示例中的 lambda 表达式就是为此目的而使用的。 对于每个仅有一个线程的进程以及在 filteredList 中选择的进程,它将返回 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
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