람다 식(Visual Basic)

람다 식은 대리자가 유효한 모든 곳에서 사용할 수 있는, 이름이 없는 함수 또는 서브루틴입니다. 람다 식은 함수 또는 서브루틴일 수 있으며, 한 줄이나 여러 줄로 구성될 수 있습니다. 현재 범위의 값을 람다 식에 전달할 수 있습니다.

참고

RemoveHandler 문은 예외입니다. RemoveHandler의 대리자 매개 변수에는 람다 식을 전달할 수 없습니다.

표준 함수 또는 서브루틴을 만드는 경우와 마찬가지로, Function 또는 Sub 키워드를 사용하여 람다 식을 만듭니다. 그러나 람다 식은 문에 포함됩니다.

다음 예제에서는 인수를 점증적으로 늘리고 값을 반환하는 람다 식입니다. 다음 예제에서는 한 줄과 여러 줄로 구성된 함수에 대한 람다 식 구문을 보여 줍니다.

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

다음 예제는 콘솔에 값을 쓰는 람다 식입니다. 다음 예제에서는 한 줄과 여러 줄로 구성된 서브루틴에 대한 람다 식 구문을 보여 줍니다.

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

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

' Write "World"
writeline2("World")

앞의 예제에서는 변수 이름에 람다 식이 할당되었습니다. 변수를 참조할 때마다 람다 식이 호출됩니다. 다음 예제와 같이 람다 식을 동시에 선언하고 호출할 수도 있습니다.

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

람다 식은 이 항목의 뒷부분에 있는 컨텍스트 단원의 예제와 같이 함수 호출의 값으로 반환될 수도 있고, 다음 예제와 같이 대리자 형식을 사용하는 매개 변수에 인수로 전달될 수도 있습니다.

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

람다 식 구문

람다 식의 구문은 표준 함수 또는 서브루틴의 구문과 유사합니다. 차이점은 다음과 같습니다.

  • 람다 식에는 이름이 없습니다.

  • 람다 식에는 Overloads 또는 Overrides와 같은 한정자가 있을 수 없습니다.

  • 한 줄로 된 람다 함수는 As 절을 사용하여 반환 형식을 지정하지 않습니다. 대신 람다 식의 본문이 평가되는 값에서 형식이 유추됩니다. 예를 들어 람다 식의 본문이 cust.City = "London"이면 반환 형식은 Boolean입니다.

  • 여러 줄로 된 람다 함수에서는 As 절을 사용하여 반환 형식을 지정하거나, 반환 형식이 유추되도록 As 절을 생략할 수 있습니다. 여러 줄로 된 람다 함수에 대해 As 절을 생략하면 반환 형식은 여러 줄로 된 람다 함수에 있는 모든 Return 문의 기준 형식으로 유추됩니다. 기준 형식이란 Return 문에 제공된 다른 모든 형식이 확대 변환될 수 있는 고유 형식입니다. 이 고유 형식을 확인할 수 없는 경우 기준 형식은 Return 문에 제공된 다른 모든 형식이 축소 변환될 수 있는 고유 형식입니다. 이러한 두 고유 형식을 모두 확인할 수 없는 경우 기준 형식은 Object입니다.

    예를 들어 Return 문에 제공된 식에 Integer, Long 및 Double 형식의 값이 포함되어 있으면 결과 형식은 Double입니다. Integer 및 Long은 모두 Double로 확대 변환되며, Double로만 확대 변환됩니다. 따라서 Double이 기준 형식이 됩니다. 자세한 내용은 확대 변환과 축소 변환(Visual Basic)을 참조하십시오.

  • 한 줄로 된 함수의 본문은 문이 아니라 값을 반환하는 식이어야 합니다. 한 줄로 된 함수에는 Return 문이 없습니다. 한 줄로 된 함수가 반환하는 값은 함수 본문에 있는 식의 값입니다.

  • 한 줄로 된 서브루틴의 본문은 한 줄로 된 문이어야 합니다.

  • 한 줄로 된 함수와 서브루틴에는 End Function 또는 End Sub 문이 포함되지 않습니다.

  • As 키워드를 사용하여 람다 식 매개 변수의 데이터 형식을 지정할 수도 있고, 매개 변수의 데이터 형식이 유추될 수도 있습니다. 모든 매개 변수에 지정된 데이터 형식이 있거나 모든 매개 변수가 유추되어야 합니다.

  • Optional 및 Paramarray 매개 변수는 허용되지 않습니다.

  • 제네릭 매개 변수가 허용되지 않습니다.

컨텍스트

람다 식과 해당 람다 식을 정의한 범위는 컨텍스트를 공유합니다. 람다 식은 포함하는 범위에서 작성된 모든 코드와 동일한 액세스 권한을 갖습니다. 여기에는 멤버 변수, 함수 및 sub, Me, 그리고 포함하는 범위에 있는 매개 변수 및 지역 변수에 대한 액세스가 포함됩니다.

포함하는 범위에 있는 지역 변수 및 매개 변수에 대한 액세스는 해당 범위의 수명 이후에도 유지될 수 있습니다. 람다 식에서 유추하는 대리자를 가비지 수집에 사용할 수 없는 한 원래 환경의 변수에 계속 액세스할 수 있습니다. 다음 예제에서 변수 target은 람다 식 playTheGame을 정의하는 메서드 makeTheGame의 지역 변수입니다. Main에서 takeAGuess에 할당되는 반환된 람다 식은 지역 변수 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

다음 예제에서는 중첩된 람다 식의 광범위한 액세스 권한을 보여 줍니다. 반환된 람다 식이 Main에서 aDel로 실행될 때는 다음 요소에 액세스합니다.

  • 반환된 람다 식을 정의한 클래스의 필드: aField

  • 반환된 람다 식을 정의한 클래스의 속성: aProp

  • 반환된 람다 식을 정의한 functionWithNestedLambda 메서드의 매개 변수: level1

  • functionWithNestedLambda의 지역 변수: localVar

  • 반환된 람다 식이 중첩된 람다 식의 매개 변수: 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

대리자 형식으로 변환

람다 식은 호환되는 대리자 형식으로 암시적으로 변환될 수 있습니다. 호환성을 위한 일반적인 요구 사항에 대한 자세한 내용은 완화된 대리자 변환(Visual Basic)을 참조하십시오. 예를 들어, 다음 코드 예제에서는 암시적으로 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

다음 코드 예제에서는 암시적으로 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

람다 식을 대리자에 할당하거나 프로시저에 인수로 전달할 때 매개 변수 이름만 지정하고 해당 데이터 형식은 생략하여 대리자에서 형식을 가져오도록 할 수 있습니다.

예제

  • 다음 예제에서는 nullable 인수에 할당된 값이 있으면 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))
    
  • 다음 예제에서는 배열에 있는 마지막 요소의 인덱스를 반환하는 람다 식을 정의합니다.

    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
    

참고 항목

작업

방법: Visual Basic에서 프로시저에 다른 프로시저 전달

방법: 람다 식 만들기(Visual Basic)

참조

Function 문(Visual Basic)

Sub 문(Visual Basic)

개념

Visual Basic의 프로시저

Visual Basic의 LINQ 소개

Nullable 값 형식(Visual Basic)

완화된 대리자 변환(Visual Basic)

기타 리소스

대리자(Visual Basic)

변경 기록

날짜

변경 내용

이유

2011년 4월

"람다 식 구문" 섹션의 여러 반환 형식에 대한 정보가 수정되었습니다.

고객 의견