Iterator (Visual Basic)

指定函式或 Get 存取子是迭代器。

備註

迭代器 會對集合執行自訂反覆運算。 迭代器會使用 Yield 陳述式,一次一個地傳回集合中的每一個元素。 當到達 Yield 陳述式時,系統會保留程式碼中的目前位置。 下一次呼叫 Iterator 函式時,便會從這個位置重新開始執行。

迭代器可以作為函式或屬性定義的 Get 存取子來進行實作。 Iterator 修飾詞會出現在 iterator 函式或 Get 存取子的宣告中。

您可以使用 For Each...Next 陳述式來從用戶端程式碼中呼叫迭代器。

iterator 函式或 Get 存取子的傳回類型可以是 IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

迭代器不能有任何 ByRef 參數。

迭代器不能出現在事件、執行個體建構函式、靜態建構函式或靜態解構函式中。

迭代器可以是一個匿名函式。 如需詳細資訊,請參閱 Iterator

使用方式

Iterator 修飾詞可用於以下內容:

範例 1

下列範例示範 iterator 函式。 iterator 函式有一個在 For…Next 迴圈內的 Yield 陳述式。 MainFor Each 陳述式主體的每次反覆運算都會建立對 Power 迭代器函式的呼叫。 每次呼叫 Iterator 函式都會執行下一個 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

如需其他範例,請參閱迭代器

另請參閱