共用方式為


Lambda 運算式 (Visual Basic)

「Lambda 運算式」(Lambda expression) 是不具名稱的函式或副程式,當委派有效時可以使用此運算式。 Lambda 運算式可以是函式或副程式,也可以是單行或多行。 您可以從目前範圍傳遞值到 Lambda 運算式。

注意事項注意事項

RemoveHandler 陳述式 (Statement) 是例外狀況 (Exception)。 您無法針對 RemoveHandler 的委派參數傳遞 Lambda 運算式。

您可以使用 Function 或 Sub 關鍵字建立 Lambda 運算式,如同建立標準函式或副程式一般。 但是,Lambda 運算式是包含在陳述式中。

下列範例是會遞增其引數並傳回值的 Lambda 運算式。 下列範例同時顯示函式的單行和多行 Lambda 運算式語法。

Dim increment1 = Function(x) x + 1
Dim increment2 = Function(x)
                     Return x + 2
                 End Function

' Write the value 2.
Console.WriteLine(increment1(1))

' Write the value 4.
Console.WriteLine(increment2(2))

下列範例是一個 Lambda 運算式,可以將值寫入至主控台。 下列範例同時顯示副程式的單行和多行 Lambda 運算式語法。

Dim writeline1 = Sub(x) Console.WriteLine(x)
Dim writeline2 = Sub(x)
                     Console.WriteLine(x)
                 End Sub

' Write "Hello".
writeline1("Hello")

' Write "World"
writeline2("World")

請注意,上述範例中 Lambda 運算式已經指派給變數名稱。 因此每當參考該變數時,便會呼叫 Lambda 運算式。 您還可以同時宣告和叫用 Lambda 運算式,如下列範例所示。

Console.WriteLine((Function(num As Integer) num + 1)(5))

Lambda 運算式可以傳回做為函式呼叫 (Function Call) 的值 (請見本主題稍後內容章節中的範例),或傳遞做為使用委派型別之參數的引數,如下範例所示。

Module Module2

    Sub Main()
        ' The following line will print Success, because 4 is even.
        testResult(4, Function(num) num Mod 2 = 0)
        ' The following line will print Failure, because 5 is not > 10.
        testResult(5, Function(num) num > 10)
    End Sub

    ' Sub testResult takes two arguments, an integer value and a 
    ' delegate function that takes an integer as input and returns
    ' a boolean. 
    ' If the function returns True for the integer argument, Success
    ' is displayed.
    ' If the function returns False for the integer argument, Failure
    ' is displayed.
    Sub testResult(ByVal value As Integer, ByVal fun As Func(Of Integer, Boolean))
        If fun(value) Then
            Console.WriteLine("Success")
        Else
            Console.WriteLine("Failure")
        End If
    End Sub

End Module

Lambda 運算式語法

Lambda 運算式的語法和標準函式或副程式語法類似。 其差異如下:

  • Lambda 運算式沒有名稱。

  • Lambda 運算式不能有修飾詞 (Modifier),例如 Overloads 或 Overrides。

  • 單行 Lambda 函式不會使用 As 子句來指定傳回型別。 而是從 Lambda 運算式評估之主體的值來推斷型別。 例如,如果 Lambda 運算式的主體是 cust.City = "London",其傳回型別為 Boolean。

  • 在多行 Lambda 函式中,您可以使用 As 子句來指定傳回型別,也可以省略 As 子句,使傳回型別成為推斷型別。 省略多行 Lambda 函式的 As 子句時,傳回型別將推斷為多行 Lambda 函式中所有 Return 陳述式的主型別。 「主型別」(Dominant Type) 是一個唯一的型別,提供給 Return 陳述式的其他所有型別都可以擴展至該型別。 如果無法決定這個唯一型別,主型別就成為提供給 Return 陳述式的其他所有型別可以縮小至的唯一型別。 如果無法決定所有這些型別,則主型別為 Object。

    例如,如果提供給 Return 陳述式的運算式含有型別值 Integer、Long 和 Double,則產生列的型別是 Double。 Integer 和 Long 都會擴展為 Double 而且僅限為 Double。 因此,Double 是主型別。 如需詳細資訊,請參閱擴展和縮小轉換 (Visual Basic)

  • 單行函式的主體必須是可以傳回值的運算式,而不是陳述式。 單行函式沒有 Return 陳述式。 單行函式傳回的值就是函式主體中運算式的值。

  • 單行副程式的主體必須是單行陳述式。

  • 單行函式和副程式不包含 End Function 或 End Sub 陳述式。

  • 您可以使用 As 關鍵字來指定 Lambda 運算式參數的資料型別,也可以推斷參數的資料型別。 所有參數都必須具有指定的資料型別,不然所有參數就都必須經過推斷。

  • 不允許 Optional 和 Paramarray 參數。

  • 不允許使用泛型參數。

內容

Lambda 運算式是和定義本身所在的範圍共用內容。 它的存取權限與包含範圍中撰寫的任何程式碼相同。 這包括對包含範圍中成員變數、函式和子函式、Me 及參數和區域變數的存取權。

對於包含範圍中的區域變數和參數的存取權期,可以延伸超過該範圍的存留期 (Lifetime)。 只要委派 (Delegate) 參考無法進行記憶體回收的 Lambda 運算式,就會保留對於原始環境中變數的存取權。 在下列範例中,變數 target 是 makeTheGame 的本機變數,而後者是 Lambda 運算式 playTheGame 在其中定義的方法。 請注意,在 Main 中指派給 takeAGuess 的傳回 Lambda 運算式,仍然可以存取本機變數 target。

Module Module6

    Sub Main()
        ' Variable takeAGuess is a Boolean function. It stores the target
        ' number that is set in makeTheGame.
        Dim takeAGuess As gameDelegate = makeTheGame()

        ' Set up the loop to play the game.
        Dim guess As Integer
        Dim gameOver = False
        While Not gameOver
            guess = CInt(InputBox("Enter a number between 1 and 10 (0 to quit)", "Guessing Game", "0"))
            ' A guess of 0 means you want to give up.
            If guess = 0 Then
                gameOver = True
            Else
                ' Tests your guess and announces whether you are correct. Method takeAGuess
                ' is called multiple times with different guesses. The target value is not 
                ' accessible from Main and is not passed in.
                gameOver = takeAGuess(guess)
                Console.WriteLine("Guess of " & guess & " is " & gameOver)
            End If
        End While

    End Sub

    Delegate Function gameDelegate(ByVal aGuess As Integer) As Boolean

    Public Function makeTheGame() As gameDelegate

        ' Generate the target number, between 1 and 10. Notice that 
        ' target is a local variable. After you return from makeTheGame,
        ' it is not directly accessible.
        Randomize()
        Dim target As Integer = CInt(Int(10 * Rnd() + 1))

        ' Print the answer if you want to be sure the game is not cheating
        ' by changing the target at each guess.
        Console.WriteLine("(Peeking at the answer) The target is " & target)

        ' The game is returned as a lambda expression. The lambda expression
        ' carries with it the environment in which it was created. This 
        ' environment includes the target number. Note that only the current
        ' guess is a parameter to the returned lambda expression, not the target. 

        ' Does the guess equal the target?
        Dim playTheGame = Function(guess As Integer) guess = target

        Return playTheGame

    End Function

End Module

下列範例示範巢狀 Lambda 運算式的廣泛存取權限。 當傳回的 Lambda 運算式是從 Main 執行為 aDel 時,它會存取下列項目:

  • 在其中進行定義的類別 (Class) 欄位:aField

  • 在其中進行定義的類別屬性:aProp

  • 在其中進行定義之方法 functionWithNestedLambda 的參數:level1

  • functionWithNestedLambda 的本機變數:localVar

  • 形成巢狀之 Lambda 運算式的參數:level2

Module Module3

    Sub Main()
        ' Create an instance of the class, with 1 as the value of 
        ' the property.
        Dim lambdaScopeDemoInstance = 
            New LambdaScopeDemoClass With {.Prop = 1}

        ' Variable aDel will be bound to the nested lambda expression  
        ' returned by the call to functionWithNestedLambda.
        ' The value 2 is sent in for parameter level1.
        Dim aDel As aDelegate = 
            lambdaScopeDemoInstance.functionWithNestedLambda(2)

        ' Now the returned lambda expression is called, with 4 as the 
        ' value of parameter level3.
        Console.WriteLine("First value returned by aDel:   " & aDel(4))

        ' Change a few values to verify that the lambda expression has 
        ' access to the variables, not just their original values.
        lambdaScopeDemoInstance.aField = 20
        lambdaScopeDemoInstance.Prop = 30
        Console.WriteLine("Second value returned by aDel: " & aDel(40))
    End Sub

    Delegate Function aDelegate(
        ByVal delParameter As Integer) As Integer

    Public Class LambdaScopeDemoClass
        Public aField As Integer = 6
        Dim aProp As Integer

        Property Prop() As Integer
            Get
                Return aProp
            End Get
            Set(ByVal value As Integer)
                aProp = value
            End Set
        End Property

        Public Function functionWithNestedLambda(
            ByVal level1 As Integer) As aDelegate

            Dim localVar As Integer = 5

            ' When the nested lambda expression is executed the first 
            ' time, as aDel from Main, the variables have these values:
            ' level1 = 2
            ' level2 = 3, after aLambda is called in the Return statement
            ' level3 = 4, after aDel is called in Main
            ' locarVar = 5
            ' aField = 6
            ' aProp = 1
            ' The second time it is executed, two values have changed:
            ' aField = 20
            ' aProp = 30
            ' level3 = 40
            Dim aLambda = Function(level2 As Integer) _
                              Function(level3 As Integer) _
                                  level1 + level2 + level3 + localVar +
                                    aField + aProp

            ' The function returns the nested lambda, with 3 as the 
            ' value of parameter level2.
            Return aLambda(3)
        End Function

    End Class
End Module

轉換為委派型別

Lambda 運算式可以隱含地轉換為相容的委派型別。 如需一般相容性需求的詳細資訊,請參閱寬鬆委派轉換 (Visual Basic)。 例如,下列程式碼範例顯示的 Lambda 運算式可隱含轉換為 Func(Of Integer, Boolean) 或相符的委派簽章。

' Explicitly specify a delegate type.
Delegate Function MultipleOfTen(ByVal num As Integer) As Boolean

' This function matches the delegate type.
Function IsMultipleOfTen(ByVal num As Integer) As Boolean
    Return num Mod 10 = 0
End Function

' This method takes an input parameter of the delegate type. 
' The checkDelegate parameter could also be of 
' type Func(Of Integer, Boolean).
Sub CheckForMultipleOfTen(ByVal values As Integer(),
                          ByRef checkDelegate As MultipleOfTen)
    For Each value In values
        If checkDelegate(value) Then
            Console.WriteLine(value & " is a multiple of ten.")
        Else
            Console.WriteLine(value & " is not a multiple of ten.")
        End If
    Next
End Sub

' This method shows both an explicitly defined delegate and a
' lambda expression passed to the same input parameter.
Sub CheckValues()
    Dim values = {5, 10, 11, 20, 40, 30, 100, 3}
    CheckForMultipleOfTen(values, AddressOf IsMultipleOfTen)
    CheckForMultipleOfTen(values, Function(num) num Mod 10 = 0)
End Sub

下列程式碼範例顯示的 Lambda 運算式可隱含轉換為 Sub(Of Double, String, Double) 或相符的委派簽章。

Module Module1
    Delegate Sub StoreCalculation(ByVal value As Double,
                                  ByVal calcType As String,
                                  ByVal result As Double)

    Sub Main()
        ' Create a DataTable to store the data.
        Dim valuesTable = New DataTable("Calculations")
        valuesTable.Columns.Add("Value", GetType(Double))
        valuesTable.Columns.Add("Calculation", GetType(String))
        valuesTable.Columns.Add("Result", GetType(Double))

        ' Define a lambda subroutine to write to the DataTable.
        Dim writeToValuesTable = Sub(value As Double, calcType As String, result As Double)
                                     Dim row = valuesTable.NewRow()
                                     row(0) = value
                                     row(1) = calcType
                                     row(2) = result
                                     valuesTable.Rows.Add(row)
                                 End Sub

        ' Define the source values.
        Dim s = {1, 2, 3, 4, 5, 6, 7, 8, 9}

        ' Perform the calculations.
        Array.ForEach(s, Sub(c) CalculateSquare(c, writeToValuesTable))
        Array.ForEach(s, Sub(c) CalculateSquareRoot(c, writeToValuesTable))

        ' Display the data.
        Console.WriteLine("Value" & vbTab & "Calculation" & vbTab & "Result")
        For Each row As DataRow In valuesTable.Rows
            Console.WriteLine(row(0).ToString() & vbTab &
                              row(1).ToString() & vbTab &
                              row(2).ToString())
        Next

    End Sub


    Sub CalculateSquare(ByVal number As Double, ByVal writeTo As StoreCalculation)
        writeTo(number, "Square     ", number ^ 2)
    End Sub

    Sub CalculateSquareRoot(ByVal number As Double, ByVal writeTo As StoreCalculation)
        writeTo(number, "Square Root", Math.Sqrt(number))
    End Sub
End Module

當您將 Lambda 運算式指派為委派或者當做引數傳遞至程序時,可以指定參數名稱但略過其資料型別,以便從委派採用型別。

範例

  • 下列範例定義 Lambda 運算式,在可為 Null 的引數具有指派值時傳回 True,而其值為 Nothing 時傳回 False。

    Dim notNothing =
      Function(num? As Integer) num IsNot Nothing
    Dim arg As Integer = 14
    Console.WriteLine("Does the argument have an assigned value?")
    Console.WriteLine(notNothing(arg))
    
  • 下列範例定義 Lambda 運算式,會傳回陣列中最後一個元素的索引。

    Dim numbers() = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    Dim lastIndex =
      Function(intArray() As Integer) intArray.Length - 1
    For i = 0 To lastIndex(numbers)
        numbers(i) += 1
    Next
    

請參閱

工作

HOW TO:在 Visual Basic 中將程序傳遞至其他程序

HOW TO:建立 Lambda 運算式 (Visual Basic)

參考

Function 陳述式 (Visual Basic)

Sub 陳述式 (Visual Basic)

概念

Visual Basic 中的程序

Visual Basic 中的 LINQ 簡介

可為 Null 的實值型別 (Visual Basic)

寬鬆委派轉換 (Visual Basic)

其他資源

委派 (Visual Basic)

變更記錄

日期

記錄

原因

2011 年 4 月

已修改關於<Lambda 運算式語法>一節中多個傳回型別的資訊。

客戶回函。