共用方式為


Iterator (Visual Basic)

表示函式或Get存取子是 iterator。

備註

Iterator 對集合進行反覆執行自訂的反覆項目。 使用 iterator 會產生陳述式來傳回一次一個集合中的每個項目。 當Yield到達陳述式時,仍可在程式碼中目前的位置。 執行已從該位置在下次重新啟動 iterator 函式所呼叫。

Iterator 可實作為函式或Get的屬性定義存取子。 Iterator修飾詞會出現在 iterator 函式宣告或Get存取子。

您從用戶端程式碼呼叫 iterator 藉由使用For Each...Next 陳述式 (Visual Basic)

將 iterator 函式的傳回型別或Get存取子可以是IEnumerableIEnumerable<T>IEnumerator,或IEnumerator<T>

Iterator 不能有任何ByRef參數。

Iterator 不可以發生在事件、 執行個體建構函式、 靜態建構函式或靜態的解構函式。

Iterator 可以是匿名函式。 如需詳細資訊,請參閱 Iterator (C# 和 Visual Basic)

如需 Iterator 的詳細資訊,請參閱 Iterator (C# 和 Visual Basic)

使用方式

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

範例

下列範例會示範一個 iterator 函式。 Iterator 函數語法包含Yield陳述式中縮排樣式下一步迴圈。 每個反覆項目中的為每個中的陳述式主體Main建立呼叫Power iterator 函式。 每次呼叫 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

下列範例會示範Get是 iterator 的存取子。 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

如需其他範例,請參閱 Iterator (C# 和 Visual Basic)

請參閱

參考

Yield 陳述式 (Visual Basic)

IteratorStateMachineAttribute

其他資源

Iterator (C# 和 Visual Basic)