반복기(Visual Basic)

함수 또는 Get 접근자가 반복기임을 지정합니다.

설명

반복기는 컬렉션에 대해 사용자 지정 반복을 수행합니다. 반복기는 Yield 문을 사용하여 컬렉션의 각 요소를 한 번에 하나씩 반환합니다. Yield 문에 도달하면 코드의 현재 위치가 보존됩니다. 다음에 반복기 함수가 호출되면 해당 위치에서 실행이 다시 시작됩니다.

반복기는 함수 또는 속성 정의의 Get 접근자로 구현될 수 있습니다. Iterator 한정자는 반복기 함수 또는 Get 접근자의 선언에 나타납니다.

For Each...Next 문을 사용하여 클라이언트 코드에서 반복기를 호출합니다.

반복기 함수 또는 Get 접근자의 반환 형식은 IEnumerable, IEnumerable<T>, IEnumerator 또는 IEnumerator<T>일 수 있습니다.

반복기는 ByRef 매개 변수를 가질 수 없습니다.

반복기는 이벤트, 인스턴스 생성자, 정적 생성자 또는 정적 소멸자에서 발생할 수 없습니다.

반복기는 익명 함수일 수 있습니다. 자세한 내용은 반복기를 참조하세요.

사용

Iterator 한정자는 다음 컨텍스트에서 사용할 수 있습니다.

예 1

다음 예에서는 반복기 함수를 보여 줍니다. 반복기 함수에는 For…Next 루프 내에 있는 Yield 문이 있습니다. MainFor Each 문 본문을 반복할 때마다 Power 반복기 함수에 대한 호출이 만들어집니다. 반복기 함수를 호출할 때마다 다음에 Yield 루프를 반복하는 도중에 For…Next 문이 실행됩니다.

Sub Main()
    For Each number In Power(2, 8)
        Console.Write(number & " ")
    Next
    ' Output: 2 4 8 16 32 64 128 256
    Console.ReadKey()
End Sub

Private Iterator Function Power(
ByVal base As Integer, ByVal highExponent As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)

    Dim result = 1

    For counter = 1 To highExponent
        result = result * base
        Yield result
    Next
End Function

예제 2

다음 예제는 반복기인 Get 접근자에 대해 설명합니다. Iterator 한정자는 속성 선언에 있습니다.

Sub Main()
    Dim theGalaxies As New Galaxies
    For Each theGalaxy In theGalaxies.NextGalaxy
        With theGalaxy
            Console.WriteLine(.Name & "  " & .MegaLightYears)
        End With
    Next
    Console.ReadKey()
End Sub

Public Class Galaxies
    Public ReadOnly Iterator Property NextGalaxy _
    As System.Collections.Generic.IEnumerable(Of Galaxy)
        Get
            Yield New Galaxy With {.Name = "Tadpole", .MegaLightYears = 400}
            Yield New Galaxy With {.Name = "Pinwheel", .MegaLightYears = 25}
            Yield New Galaxy With {.Name = "Milky Way", .MegaLightYears = 0}
            Yield New Galaxy With {.Name = "Andromeda", .MegaLightYears = 3}
        End Get
    End Property
End Class

Public Class Galaxy
    Public Property Name As String
    Public Property MegaLightYears As Integer
End Class

추가 예를 보려면 반복기를 참조하세요.

참고 항목