Lambda 運算式 (Visual Basic)Lambda Expressions (Visual Basic)

Lambda 運算式是一個不含名稱的函式或副程式,可以在委派有效的任何地方使用。A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda 運算式可以是函數或副程式,而且可以是單行或多行。Lambda expressions can be functions or subroutines and can be single-line or multi-line. 您可以將值從目前範圍傳遞至 lambda 運算式。You can pass values from the current scope to a lambda expression.

注意

@No__t_0 語句是例外狀況。The RemoveHandler statement is an exception. 您無法在中傳遞 lambda 運算式,以取得 RemoveHandler 的委派參數。You cannot pass a lambda expression in for the delegate parameter of RemoveHandler.

您可以使用 FunctionSub 關鍵字來建立 lambda 運算式,就如同建立標準函數或副程式一樣。You create lambda expressions by using the Function or Sub keyword, just as you create a standard function or subroutine. 不過,lambda 運算式會包含在語句中。However, lambda expressions are included in a statement.

下列範例是 lambda 運算式,它會遞增其引數並傳回值。The following example is a lambda expression that increments its argument and returns the value. 此範例會顯示函數的單行和多行 lambda 運算式語法。The example shows both the single-line and multi-line lambda expression syntax for a function.

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 運算式。The following example is a lambda expression that writes a value to the console. 此範例會顯示副程式的單行和多行 lambda 運算式語法。The example shows both the single-line and multi-line lambda expression syntax for a subroutine.

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 運算式會指派給變數名稱。Notice that in the previous examples the lambda expressions are assigned to a variable name. 每當您參考變數時,就會叫用 lambda 運算式。Whenever you refer to the variable, you invoke the lambda expression. 您也可以同時宣告和叫用 lambda 運算式,如下列範例所示。You can also declare and invoke a lambda expression at the same time, as shown in the following example.

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

Lambda 運算式可以當做函式呼叫的值傳回(如本主題稍後的內容章節中的範例所示),或當做引數傳遞給採用委派類型的參數,如下列範例所示。A lambda expression can be returned as the value of a function call (as is shown in the example in the Context section later in this topic), or passed in as an argument to a parameter that takes a delegate type, as shown in the following example.

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 Expression Syntax

Lambda 運算式的語法類似于標準函式或副程式。The syntax of a lambda expression resembles that of a standard function or subroutine. 差異如下:The differences are as follows:

  • Lambda 運算式沒有名稱。A lambda expression does not have a name.

  • Lambda 運算式不能有修飾詞,例如 OverloadsOverridesLambda expressions cannot have modifiers, such as Overloads or Overrides.

  • 單行 lambda 函數不會使用 As 子句來指定傳回類型。Single-line lambda functions do not use an As clause to designate the return type. 相反地,型別是從 lambda 運算式主體評估為的值推斷而來。Instead, the type is inferred from the value that the body of the lambda expression evaluates to. 例如,如果 lambda 運算式的主體是 cust.City = "London",則其傳回型別會 BooleanFor example, if the body of the lambda expression is cust.City = "London", its return type is Boolean.

  • 在多行 lambda 函式中,您可以使用 As 子句來指定傳回型別,或省略 As 子句,以推斷傳回型別。In multi-line lambda functions, you can either specify a return type by using an As clause, or omit the As clause so that the return type is inferred. 針對多行 lambda 函數省略 As 子句時,會將傳回型別推斷為多行 lambda 函式中所有 Return 語句的主要型別。When the As clause is omitted for a multi-line lambda function, the return type is inferred to be the dominant type from all the Return statements in the multi-line lambda function. 主要類型是所有其他類型都可以擴展的唯一類型。The dominant type is a unique type that all other types can widen to. 如果無法判斷此唯一類型,則主要類型是陣列中所有其他類型都可以縮小為的唯一類型。If this unique type cannot be determined, the dominant type is the unique type that all other types in the array can narrow to. 如果這些類型皆無法決定,則主類型為 ObjectIf neither of these unique types can be determined, the dominant type is Object. 在此情況下,如果 Option Strict 設定為 On,就會發生編譯器錯誤。In this case, if Option Strict is set to On, a compiler error occurs.

    例如,如果提供給 Return 語句的運算式包含類型 IntegerLongDouble 的值,則產生的陣列會是 Double 類型。For example, if the expressions supplied to the Return statement contain values of type Integer, Long, and Double, the resulting array is of type Double. @No__t_0 和 Long 會擴展到 Double,而且只會 DoubleBoth Integer and Long widen to Double and only Double. 因此, Double 是主類型。Therefore, Double is the dominant type. 如需詳細資訊,請參閱 Widening and Narrowing ConversionsFor more information, see Widening and Narrowing Conversions.

  • 單行函數的主體必須是傳回值的運算式,而不是語句。The body of a single-line function must be an expression that returns a value, not a statement. 沒有適用于單行函式的 Return 語句。There is no Return statement for single-line functions. 單行函式所傳回的值是函數主體中的運算式值。The value returned by the single-line function is the value of the expression in the body of the function.

  • 單行副程式的主體必須是單行語句。The body of a single-line subroutine must be single-line statement.

  • 單行函數和副程式不包含 End FunctionEnd Sub 語句。Single-line functions and subroutines do not include an End Function or End Sub statement.

  • 您可以使用 As 關鍵字來指定 lambda 運算式參數的資料類型,或者可以推斷參數的資料類型。You can specify the data type of a lambda expression parameter by using the As keyword, or the data type of the parameter can be inferred. 所有參數都必須具有指定的資料類型,否則必須推斷全部。Either all parameters must have specified data types or all must be inferred.

  • 不允許 OptionalParamarray 參數。Optional and Paramarray parameters are not permitted.

  • 不允許泛型參數。Generic parameters are not permitted.

非同步 LambdaAsync Lambdas

您可以使用AsyncAwait 運算子關鍵字,輕鬆建立結合非同步處理的 lambda 運算式和語句。You can easily create lambda expressions and statements that incorporate asynchronous processing by using the Async and Await Operator keywords. 例如,下列 Windows Form 範例包含呼叫並等候非同步方法 ExampleMethodAsync的事件處理常式。For example, the following Windows Forms example contains an event handler that calls and awaits an async method, ExampleMethodAsync.

Public Class Form1

    Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' ExampleMethodAsync returns a Task.
        Await ExampleMethodAsync()
        TextBox1.Text = vbCrLf & "Control returned to button1_Click."
    End Sub

    Async Function ExampleMethodAsync() As Task
        ' The following line simulates a task-returning asynchronous process.
        Await Task.Delay(1000)
    End Function

End Class

您可以在AddHandler 語句中使用非同步 lambda 來加入相同的事件處理常式。You can add the same event handler by using an async lambda in an AddHandler Statement. 若要加入這個處理常式,請將 Async 修飾詞加入至 Lambda 參數清單前面,如下列範例所示。To add this handler, add an Async modifier before the lambda parameter list, as the following example shows.

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        AddHandler Button1.Click,
            Async Sub(sender1, e1)
                ' ExampleMethodAsync returns a Task.
                Await ExampleMethodAsync()
                TextBox1.Text = vbCrLf & "Control returned to Button1_ Click."
            End Sub
    End Sub

    Async Function ExampleMethodAsync() As Task
        ' The following line simulates a task-returning asynchronous process.
        Await Task.Delay(1000)
    End Function

End Class

如需如何建立和使用非同步方法的詳細資訊,請參閱使用 async 和 Await 進行非同步程式設計For more information about how to create and use async methods, see Asynchronous Programming with Async and Await.

內容Context

Lambda 運算式會與其定義所在的範圍共用其內容。A lambda expression shares its context with the scope within which it is defined. 其存取權限與在包含範圍中撰寫的任何程式碼相同。It has the same access rights as any code written in the containing scope. 這包括存取成員變數、函式和子函數、Me,以及包含範圍內的參數和區域變數。This includes access to member variables, functions and subs, Me, and parameters and local variables in the containing scope.

存取包含範圍中的本機變數和參數,可以延伸超出該範圍的存留期。Access to local variables and parameters in the containing scope can extend beyond the lifetime of that scope. 只要參考 lambda 運算式的委派無法用於垃圾收集,就會保留原始環境中變數的存取權。As long as a delegate referring to a lambda expression is not available to garbage collection, access to the variables in the original environment is retained. 在下列範例中,變數 targetmakeTheGame 的區域,這是定義 lambda 運算式 playTheGame 的方法。In the following example, variable target is local to makeTheGame, the method in which the lambda expression playTheGame is defined. 請注意,指派給 MaintakeAGuess 的傳回 lambda 運算式仍然可以存取本機變數 targetNote that the returned lambda expression, assigned to takeAGuess in Main, still has access to the local variable 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 運算式的範圍存取權限。The following example demonstrates the wide range of access rights of the nested lambda expression. 當從 Main 執行傳回的 lambda 運算式做為 aDel 時,它會存取這些元素:When the returned lambda expression is executed from Main as aDel, it accesses these elements:

  • 其定義所在類別的欄位: aFieldA field of the class in which it is defined: aField

  • 定義所在之類別的屬性: aPropA property of the class in which it is defined: aProp

  • 方法 functionWithNestedLambda 的參數,在其中定義: level1A parameter of method functionWithNestedLambda, in which it is defined: level1

  • @No__t_0 的本機變數: localVarA local variable of functionWithNestedLambda: localVar

  • Lambda 運算式的參數,其在其中嵌套: level2A parameter of the lambda expression in which it is nested: 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
            ' localVar = 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

轉換成委派類型Converting to a Delegate Type

Lambda 運算式可以隱含地轉換成相容的委派類型。A lambda expression can be implicitly converted to a compatible delegate type. 如需相容性一般需求的相關資訊,請參閱寬鬆委派轉換For information about the general requirements for compatibility, see Relaxed Delegate Conversion. 例如,下列程式碼範例顯示隱含轉換成 Func(Of Integer, Boolean) 或相符的委派簽章的 lambda 運算式。For example, the following code example shows a lambda expression that implicitly converts to Func(Of Integer, Boolean) or a matching delegate signature.

' 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) 或相符的委派簽章。The following code example shows a lambda expression that implicitly converts to Sub(Of Double, String, Double) or a matching delegate signature.

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 運算式指派給委派,或將它們當做引數傳遞給程式時,您可以指定參數名稱但省略其資料類型,讓型別可以從委派取得。When you assign lambda expressions to delegates or pass them as arguments to procedures, you can specify the parameter names but omit their data types, letting the types be taken from the delegate.

範例Examples

  • 下列範例會定義 lambda 運算式,如果可為 null 的引數具有指派的值,則會傳回 True,如果 Nothing 其值,則會 FalseThe following example defines a lambda expression that returns True if the nullable argument has an assigned value, and False if its value is Nothing.

    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 運算式,以傳回陣列中最後一個元素的索引。The following example defines a lambda expression that returns the index of the last element in an array.

    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
    

請參閱See also