Compartilhar via


Expressões Lambda (Visual Basic)

A expressão lambda é uma função ou sub-rotina sem um nome que pode ser usado sempre que um delegado é válido. As expressões lambda podem ser funções ou sub-rotinas e podem ser a únicalinha ou multi -linha. Você pode passar valores do escopo atual para uma expressão lambda.

ObservaçãoObservação

The RemoveHandler statement is an exception. You cannot pass a lambda expression in for the delegate parameter of RemoveHandler.

Você criar as expressões lambda, usando o Function ou Sub palavra-chave, assim como você criar um padrão de função ou sub-rotina. No entanto, as expressões lambda são incluídas em uma demonstrativo.

The following example is a lambda expression that increments its argument and returns the value. O exemplo mostra a únicalinha e o multi -linha lambda sintaxe de expressão para uma função.

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))

O exemplo a seguir é uma expressão lambda que grava um valor para o console. O exemplo mostra a únicalinha e o multi -linha lambda sintaxe de expressão de uma sub-rotina.

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

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

' Write "World"
writeline2("World")

Observe que, nos exemplos anteriores, as expressões lambda são atribuídas a um nome de variável . Sempre que você se referir à variável, você pode chamar a expressão lambda. Você também pode declarar e chamar uma expressão lambda, ao mesmo tempo, conforme mostrado no exemplo a seguir.

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

Uma expressão lambda pode ser retornada como o valor de uma chamada de função (como é mostrado no exemplo de contexto seção mais adiante neste tópico), ou passado como um argumento para um parâmetro que leva um tipo de delegado, como mostrado no exemplo a seguir.

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

A sintaxe de uma expressão lambda é semelhante ao de um padrão de função ou sub-rotina. The differences are as follows:

  • A lambda expression does not have a name.

  • Lambda expressions cannot have modifiers, such as Overloads or Overrides.

  • Funções de lambda delinha única - não usarem um As cláusula para designar o tipo de retorno. Instead, the type is inferred from the value that the body of the lambda expression evaluates to. For example, if the body of the lambda expression is cust.City = "London", its return type is Boolean.

  • Em várias funções de lambda delinha , você pode especificar um tipo de retorno por meio de um As cláusula, ou omitir a As cláusula para que o tipo de retorno é inferido. Quando o As cláusula é omitida para uma multi -linha lambda função, o tipo de retorno é inferido para ser do tipo dominante de todos os Return declarações na multi -linha lambda de função. O tipo dominante é um tipo exclusivo que todos os outros tipos de literal de matriz podem ampliar a. Se este tipo exclusivo não pode ser determinado, o tipo dominante é o tipo exclusivo que todos os outros tipos de matriz podem restringir a pesquisa. Se nenhum desses tipos exclusivos pode ser determinado o tipo de dominante é Object. Por exemplo, se a lista de valores fornecidos para o literal de matriz contém os valores do tipo Integer, Long, e Double, a matriz resultante é do tipo Double. Ambos Integer e Long aumentarão para Double e apenas Double. Portanto, Double é o tipo dominante. For more information, see Conversões de expansão e restrição (Visual Basic).

  • O corpo de uma únicalinha função deve ser uma expressão que retorna um valor, não é uma demonstrativo. Não há nenhum Returndedemonstrativo para várias funções delinha . O valor retornado pela single -linha função é o valor da expressão no corpo da função.

  • O corpo de uma sub-rotina delinha única - deve ser a únicalinha demonstrativo.

  • Únicalinha funções e sub-rotinas não incluem um End Function ou End Sub demonstrativo.

  • Você pode especificar o tipo de dados de expressão lambda parâmetro usando a As palavra-chaveou o tipo de dados do parâmetro pode ser deduzido. Either all parameters must have specified data types or all must be inferred.

  • Optionale Paramarray parâmetros não são permitidos.

  • Generic parameters are not permitted.

Context

Uma expressão lambda compartilha seu contexto com o escopo dentro do qual ele está definido. Ele tem os mesmos direitos de acesso de qualquer código escrito no escopoque contém. Isso inclui acesso a variáveis de membro, funções e sub-rotinas, Mee parâmetros e variáveis locais no escopocontendo.

Acesso a variáveis locais e parâmetros no escopo contendo pode se estender além do tempo de vida desse escopo. 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. In the following example, variable target is local to makeTheGame, the method in which the lambda expression playTheGame is defined. Note 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

The following example demonstrates the wide range of access rights of the nested lambda expression. When the returned lambda expression is executed from Main as aDel, it accesses these elements:

  • A field of the class in which it is defined: aField

  • A property of the class in which it is defined: aProp

  • Um parâmetro do método functionWithNestedLambda, em que é definido: level1

  • Uma variável de local de functionWithNestedLambda: localVar

  • A 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
            ' 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

Converting to a Delegate Type

A lambda expression can be implicitly converted to a compatible delegate type. Para obter informações sobre os requisitos gerais para compatibilidade, consulte Conversão de delegado reduzida (Visual Basic). Por exemplo, o exemplo de código a seguir mostra uma expressão lambda que converte implicitamente Func(Of Integer, Boolean) ou delegar a assinaturacorrespondente.

' 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

O exemplo de código a seguir mostra uma expressão lambda que converte implicitamente Sub(Of Double, String, Double) ou delegar a assinaturacorrespondente.

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

Quando você atribuir as expressões lambda para representantes ou passá-las como argumentos para procedimentos, você pode especificar os nomes de parâmetro mas omitir seus tipos de dados, permitindo que os tipos a ser executada a partir do delegado.

Examples

  • O exemplo a seguir define uma expressão lambda que retorna True se o argumento de anulável tiver um valor atribuído, e False se o seu valor é 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))
    
  • O exemplo a seguir define uma expressão lambda que retorna o índice do último elemento em uma matriz.

    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
    

Consulte também

Tarefas

Como: Passar Procedimentos para outro Procedimento em Visual Basic.

Como: Criar uma expressão Lambda (Visual Basic)

Referência

Instrução Function (Visual Basic)

Instrução Sub (Visual Basic)

Conceitos

Procedimentos no Visual Basic

Introdução ao LINQ no Visual Basic

Tipos de valor anulável (Visual Basic)

Conversão de delegado reduzida (Visual Basic)

Outros recursos

Delegados (Visual Basic)