迭代器 (Visual Basic)

指定函数或 Get 访问器是迭代器。

备注

迭代器 对集合的自定义迭代。 迭代器使用 yield 语句返回集合中的每个元素一个节点。 当 Yield 语句时,代码的当前位置保留。 执行从该位置下次重新启动迭代器函数调用。

迭代器可以实现为函数或作为属性定义的 Get 访问器。 Iterator 修饰符出现在迭代器函数或 Get 访问器的说明。

使用 For Each...Next 语句 (Visual Basic),请调用从客户端代码中的迭代器。

迭代器函数或 Get 访问器的返回类型可以是 IEnumerableIEnumerableIEnumeratorIEnumerator

迭代器不能有任何 ByRef 参数。

迭代器在事件、实例构造函数、静态构造函数或静态析构函数不能出现。

迭代器可以是匿名函数。 有关更多信息,请参见 迭代器(C# 和 Visual Basic)

有关迭代器的更多信息,请参见迭代器(C# 和 Visual Basic)

用法

Iterator 修饰符可用于下面的上下文中:

示例

下面的示例演示一个迭代器函数。 迭代器函数具有是在 for…next 循环内的一个 Yield 语句。 对于每个 语句体的每个迭代在 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

下面的示例演示是迭代器的 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

有关其他示例,请参见迭代器(C# 和 Visual Basic)

请参见

参考

Yield 语句 (Visual Basic)

IteratorStateMachineAttribute

其他资源

迭代器(C# 和 Visual Basic)