Condividi tramite


Espressioni lambda (Visual Basic)

Un'espressione lambda è una funzione o una subroutine senza un nome che può essere usato ovunque un delegato sia valido. Le espressioni lambda possono essere funzioni o subroutine e possono essere a riga singola o su più righe. È possibile passare valori dall'ambito corrente a un'espressione lambda.

Annotazioni

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

Le espressioni lambda vengono create usando la Function parola chiave o Sub , proprio come si crea una funzione o una subroutine standard. Tuttavia, le espressioni lambda vengono incluse in un'istruzione .

L'esempio seguente è un'espressione lambda che incrementa l'argomento e restituisce il valore . L'esempio mostra sia la sintassi dell'espressione lambda a riga singola che quella multilinea per una funzione.

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

L'esempio seguente è un'espressione lambda che scrive un valore nella console. L'esempio mostra sia la sintassi dell'espressione lambda a riga singola che quella multilinea per una 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")

Si noti che negli esempi precedenti le espressioni lambda vengono assegnate a un nome di variabile. Ogni volta che si fa riferimento alla variabile, si richiama l'espressione lambda. È anche possibile dichiarare e richiamare contemporaneamente un'espressione lambda, come illustrato nell'esempio seguente.

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

Un'espressione lambda può essere restituita come valore di una chiamata di funzione (come illustrato nell'esempio nella sezione Context più avanti in questo argomento) o passata come argomento a un parametro che accetta un tipo delegato, come illustrato nell'esempio seguente.

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

Sintassi dell'espressione lambda

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

  • Un'espressione lambda non ha un nome.

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

  • Le funzioni lambda a riga singola non usano una As clausola per designare il tipo restituito. Al contrario, il tipo viene dedotto dal valore che il corpo dell'espressione lambda restituisce. Ad esempio, se il corpo dell'espressione lambda è cust.City = "London", il tipo restituito è Boolean.

  • Nelle funzioni lambda su più righe è possibile specificare un tipo restituito usando una As clausola oppure omettere la As clausola in modo che venga dedotto il tipo restituito. Quando la As clausola viene omessa per una funzione lambda a più righe, il tipo restituito viene dedotto come tipo dominante da tutte le Return istruzioni nella funzione lambda a più righe. Il tipo dominante è un tipo univoco a cui tutti gli altri tipi possono essere ampliati. Se non è possibile determinare questo tipo univoco, il tipo dominante è il tipo univoco a cui tutti gli altri tipi della matrice possono essere limitati. Se nessuno di questi tipi univoci può essere determinato, il tipo dominante è Object. In questo caso, se Option Strict è impostato su On, si verifica un errore del compilatore.

    Ad esempio, se le espressioni fornite all'istruzione Return contengono valori di tipo Integer, Longe Double, la matrice risultante è di tipo Double. Sia Integer che Long si espandono a Double e solo Double. Pertanto, Double è il tipo dominante. Per altre informazioni, vedere Conversioni di tipo Widening and Narrowing.

  • Il corpo di una funzione a riga singola deve essere un'espressione che restituisce un valore, non un'istruzione . Non esiste alcuna Return istruzione per le funzioni a riga singola. Il valore restituito dalla funzione a riga singola è il valore dell'espressione nel corpo della funzione.

  • Il corpo di una subroutine a riga singola deve essere un'istruzione a riga singola.

  • Le funzioni a riga singola e le subroutine non includono un'istruzione End Function o End Sub .

  • È possibile specificare il tipo di dati di un parametro di espressione lambda usando la As parola chiave oppure è possibile dedurre il tipo di dati del parametro. Tutti i parametri devono avere tipi di dati specificati o tutti devono essere dedotti.

  • I parametri Optional e Paramarray non sono consentiti.

  • I parametri generici non sono consentiti.

Espressioni lambda asincrone

È possibile creare facilmente espressioni lambda e istruzioni che incorporano l'elaborazione asincrona usando le parole chiave Async e Await Operator . L'esempio di Windows Form seguente, ad esempio, contiene un gestore eventi che chiama e attende un metodo asincrono, 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

È possibile aggiungere lo stesso gestore eventi usando un'espressione lambda asincrona in un'istruzione AddHandler. Per aggiungere questo gestore, aggiungere un Async modificatore prima dell'elenco di parametri lambda, come illustrato nell'esempio seguente.

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

Per altre informazioni su come creare e usare metodi asincroni, vedere Programmazione asincrona con Async e Await.

Contesto

Un'espressione lambda condivide il contesto con l'ambito all'interno del quale è definito. Ha gli stessi diritti di accesso di qualsiasi codice scritto nell'ambito contenitore. Ciò include l'accesso a variabili membro, funzioni e sottosezioni, Meparametri e variabili locali nell'ambito contenitore.

L'accesso a variabili e parametri locali nell'ambito contenitore può estendersi oltre la durata di tale ambito. Se un delegato che fa riferimento a un'espressione lambda non è disponibile per la Garbage Collection, l'accesso alle variabili nell'ambiente originale viene mantenuto. Nell'esempio seguente la variabile target è locale in makeTheGame, il metodo in cui viene definita l'espressione playTheGame lambda. Si noti che l'espressione lambda restituita, assegnata a takeAGuess in Main, ha comunque accesso alla variabile targetlocale .

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

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

  • Campo della classe in cui è definito: aField

  • Proprietà della classe in cui è definita: aProp

  • Parametro del metodo functionWithNestedLambda, in cui è definito: level1

  • Variabile locale di functionWithNestedLambda: localVar

  • Parametro dell'espressione lambda in cui è annidato: 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

Conversione in un tipo delegato

Un'espressione lambda può essere convertita in modo implicito in un tipo delegato compatibile. Per informazioni sui requisiti generali per la compatibilità, vedere Relaxed Delegate Conversion. Nell'esempio di codice seguente, ad esempio, viene illustrata un'espressione lambda che converte Func(Of Integer, Boolean) in modo implicito o in una firma del delegato corrispondente.

' 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

Nell'esempio di codice seguente viene illustrata un'espressione lambda che converte Sub(Of Double, String, Double) in modo implicito o in una firma del delegato corrispondente.

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 si assegnano espressioni lambda ai delegati o le si passa come argomenti alle routine, è possibile specificare i nomi dei parametri, ma omettere i relativi tipi di dati, consentendo di ottenere i tipi dal delegato.

Esempi

  • Nell'esempio seguente viene definita un'espressione lambda che restituisce True se l'argomento del tipo di valore 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 seguente viene definita un'espressione lambda che restituisce l'indice dell'ultimo elemento in una matrice.

    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
    

Vedere anche