Muokkaa

Jaa


Iterator (Visual Basic)

Specifies that a function or Get accessor is an iterator.

Remarks

An iterator performs a custom iteration over a collection. An iterator uses the Yield statement to return each element in the collection one at a time. When a Yield statement is reached, the current location in code is retained. Execution is restarted from that location the next time that the iterator function is called.

An iterator can be implemented as a function or as a Get accessor of a property definition. The Iterator modifier appears in the declaration of the iterator function or Get accessor.

You call an iterator from client code by using a For Each...Next Statement.

The return type of an iterator function or Get accessor can be IEnumerable, IEnumerable<T>, IEnumerator, or IEnumerator<T>.

An iterator cannot have any ByRef parameters.

An iterator cannot occur in an event, instance constructor, static constructor, or static destructor.

An iterator can be an anonymous function. For more information, see Iterators.

Usage

The Iterator modifier can be used in these contexts:

Example 1

The following example demonstrates an iterator function. The iterator function has a Yield statement that is inside a For…Next loop. Each iteration of the For Each statement body in Main creates a call to the Power iterator function. Each call to the iterator function proceeds to the next execution of the Yield statement, which occurs during the next iteration of the For…Next loop.

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

Example 2

The following example demonstrates a Get accessor that is an iterator. The Iterator modifier is in the property declaration.

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

For additional examples, see Iterators.

See also