Share via


Espressioni lambda

Aggiornamento: novembre 2007

Una espressione lambda è una funzione senza nome, che calcola e restituisce un singolo valore. Le espressioni lambda possono essere utilizzate con un tipo delegato valido.

Nota:

Fa eccezione l''istruzione RemoveHandler. Non è possibile passare un'espressione lambda in per il parametro del delegato di RemoveHandler.

Nell'esempio seguente viene illustrata un'espressione lambda che incrementa il proprio argomento e restituisce il valore.

Function (num As Integer) num + 1

In quanto tale, un'espressione lambda può essere utilizzata unicamente come parte di un'istruzione.

Ad esempio, è possibile assegnare la funzione a un nome di variabile, in particolare se si desidera utilizzarla più volte.

Dim add1 = Function(num As Integer) num + 1

Per chiamare la funzione, inviare un valore per il parametro.

' The following line prints 6.
Console.WriteLine(add1(5))

In alternativa, è possibile dichiarare ed eseguire contemporaneamente la funzione.

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

Un'espressione lambda può essere restituita come valore di una chiamata di funzione (come viene illustrato nell'esempio della sezione Context, più avanti in questo argomento) o passata come argomento a un parametro del delegato. Nell'esempio seguente, le espressioni lambda di Booleano vengono passate come argomento al metodo testResult. Il metodo applica il test booleano all'argomento integer value. Quando l'espressione lambda restituisce True, se applicata a value, viene visualizzato il messaggio "Operazione riuscita". Quando l'espressione lambda restituisce False viene visualizzato il messaggio "Operazione non riuscita".

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 
    ' Boolean function. 
    ' 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

Espressioni lambda nelle query

In LINQ (Language-Integrated Query), molti degli operatori di query standard hanno espressioni lambda sottostanti. Il compilatore crea le espressioni lambda per acquisire i calcoli definiti nei metodi di query fondamentali, ad esempio Where, Select,Order By, Take While e altri.

Si consideri ad esempio la seguente query:

Dim londonCusts = From cust In db.Customers 
                  Where cust.City = "London" 
                  Select cust

Questa esempio viene compilato nel codice riportato di seguito.

Dim londonCusts = db.Customers _
    .Where(Function(cust) cust.City = "London") _
    .Select(Function(cust) cust)

Per ulteriori informazioni sui metodi di query, vedere Query (Visual Basic).

Sintassi delle espressioni lambda

La sintassi di un'espressione lambda è simile a quella di una funzione standard. Le differenze sono le seguenti.

  • Un'espressione lambda non possiede un nome.

  • Le espressioni lambda non possono avere modificatori, ad esempio Overloads o Overrides.

  • Le espressioni lambda non utilizzano una clausola As per definire il tipo restituito della funzione. Invece, il tipo viene dedotto dal valore calcolato dal corpo dell'espressione lambda . Ad esempio, se il corpo dell'espressione lambda è Where cust.City = "London", il relativo tipo restituito è Boolean.

  • Il corpo della funzione deve essere un'espressione, non un'istruzione. Il corpo può essere costituito da una chiamata a una routine di funzione, ma non da una chiamata a una subroutine.

  • Non è presente l'istruzione Return. Il valore restituito dalla funzione è il valore dell'espressione nel corpo della funzione.

  • Non è presente l'istruzione End Function.

  • Tutti i parametri devono avere tipi di dati specificati oppure tutti devono essere dedotti.

  • Non sono permessi parametri Optional e Paramarray .

  • Non sono permessi parametri generici.

Come conseguenza di queste restrizioni e della modalità in cui le espressioni lambda vengono utilizzate, di solito sono corte e non complicate.

Context

Un'espressione lambda condivide il contesto con il metodo all'interno dell quale è definita. Possiede le stesse autorizzazioni di accesso di qualsiasi codice scritto nel metodo che contiene. Incluso l' accesso alle variabili membro, a funzioni e subroutine, Mee parametri e variabili locali nel metodo che contiene.

L'accesso a variabili locali e parametri nel metodo che contiene si può estendere oltre la durata di quel metodo. Finché un delegato che fa riferimento a un'espressione lambda non viene reso disponibile per la garbage collection, viene mantenuto l'accesso alle variabili nell'ambiente originale. Nell'esempio seguente, la variabile target è locale per makeTheGame, il metodo nel quale viene definita l'espressione lambda playTheGame. Si noti che l'espressione lambda restituita, assegnata a takeAGuess in Main, dispone ancora dell'accesso alla variabile locale target.

Module Module1

    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

Nell'esempio seguente viene illustrata l'ampia gamma di autorizzazioni di accesso dell'espressione lambda nidificata. Quando l'espressione lambda restituita viene eseguita da Main come aDel, accede a questi elementi:

  • Un campo della classe in cui viene definito: aField

  • Una proprietà della classe in cui viene definito: aProp

  • Un parametro del metodo functionWithNestedLambda nel quale è definito: level1

  • Una variabile locale di functionWithNestedLambda: localVar

  • Un parametro dell'espressione lambda nella quale è nidificata: 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

Conversione a un tipo delegato

Un'espressione lambda può essere convertita implicitamente a un tipo delegato compatibile. Per ulteriori informazioni sui requisiti generali per la compatibilità, vedere Conversione di tipo relaxed del delegato.

Inoltre quando si assegnano espressioni lambda ai delegati, è possibile specificare i nomi del parametro ma omettere i relativi tipi di dati, permettendo che i tipi siano ricavati dal delegato. Nell'esempio seguente, un'espressione lambda viene assegnata a una variabile denominata del di tipo ExampleDel, un delegato che accetta due parametri, un valore integer e una stringa. I tipi di dati dei parametri nell'espressione lambda non sono specificati. Tuttavia, del richiede un argomento integer e un argomento di tipo stringa, come specificato nella definizione di ExampleDel.

' Definition of function delegate ExampleDel.
Delegate Function ExampleDel(ByVal arg1 As Integer, _
                             ByVal arg2 As String) As Integer
' Declaration of del as an instance of ExampleDel, with no data 
' type specified for the parameters, m and s.
Dim del As ExampleDel = Function(m, s) m

' Valid call to del, sending in an integer and a string.
Console.WriteLine(del(7, "up"))

' Neither of these calls is valid. Function del requires an integer
' argument and a string argument.
' Not valid.
' Console.WriteLine(del(7, 3))
' Console.WriteLine(del("abc"))

Esempi

  • Nell'esempio riportato di seguito viene definita un'espressione lambda che restituisce True se l'argomento nullable ha un valore assegnato e False se il relativo valore è 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))
    
  • Nell'esempio riportato di seguito viene definita un'espressione lambda che restituisce l'indice dell'ultimo elemento in una matrice.

    Dim numbers() As Integer = {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) = numbers(i) + 1
    Next
    

Vedere anche

Attività

Procedura: passare una routine a un'altra routine in Visual Basic

Procedura: creare un'espressione lambda

Concetti

Routine in Visual Basic

Introduzione a LINQ in Visual Basic

Delegati e operatore AddressOf

Tipi di valori nullable

Conversione di tipo relaxed del delegato

Riferimenti

Istruzione Function (Visual Basic)