迭代器 (Visual Basic)

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

注解

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

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

使用 For Each... 从客户端代码调用迭代器 ...Next 语句

迭代器函数或Get访问器的返回类型可以是IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

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

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

迭代器可以是匿名函数。 有关更多信息,请参见 迭代器

用法

修饰 Iterator 符可用于以下上下文:

示例 1

以下示例演示迭代器函数。 迭代器函数有一个Yield位于 For... 中的语句下一个循环。 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

有关其他示例,请参阅 迭代器

另请参阅