다음을 통해 공유


반복기(Visual Basic)

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

비고

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

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

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

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

반복기에는 매개 변수가 있을 ByRef 수 없습니다.

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

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

사용법

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

예제 1

다음 예제에서는 반복기 함수를 보여 줍니다. 반복기 함수에는 YieldFor... 다음 루프. For Each 문 본문의 각 반복은 Main 반복기 함수에 대한 호출을 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

추가 예제는 반복기를 참조하세요.

참고하십시오