迭代器 (Visual Basic)

迭代器可用于单步执行列表和数组等集合。

迭代器方法或 get 访问器对集合执行自定义迭代。 迭代器方法使用 Yield 语句一次返回每个元素。 到达 Yield 语句时,会记住当前在代码中的位置。 下次调用迭代器函数时,将从该位置重启执行。

你可以通过在客户端代码中使用 For Each…Next 语句或 LINQ 查询来使用迭代器。

在以下示例中,For Each 循环的第一次迭代会使执行从SomeNumbers迭代器方法继续,直到遇到第一个Yield语句。 此迭代返回值 3,并保留迭代器方法中的当前位置。 在循环的下一次迭代中,迭代器方法中的执行从其离开的位置继续执行,在到达 Yield 语句时再次停止。 此迭代返回值 5,迭代器方法中的当前位置再次保留。 当到达迭代器方法的末尾时,循环将完成。

Sub Main()
    For Each number As Integer In SomeNumbers()
        Console.Write(number & " ")
    Next
    ' Output: 3 5 8
    Console.ReadKey()
End Sub

Private Iterator Function SomeNumbers() As System.Collections.IEnumerable
    Yield 3
    Yield 5
    Yield 8
End Function

迭代器方法或get访问器的返回类型可以是IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

可以使用 Exit FunctionReturn 语句结束迭代。

Visual Basic 迭代器函数或 get 访问器声明包括 迭代器 修饰符。

迭代器是在 Visual Studio 2012 的 Visual Basic 中引入的。

注释

对于本文中除简单迭代器示例以外的所有示例,请为 System.Collections 命名空间加入 System.Collections.Generic 语句。

简单迭代器

以下示例有一个位于 Yield 循环中的单个 语句。 在 Main 中,For Each 语句体的每次迭代都会创建一个对迭代器函数的调用,并将继续到下一个 Yield 语句。

Sub Main()
    For Each number As Integer In EvenSequence(5, 18)
        Console.Write(number & " ")
    Next
    ' Output: 6 8 10 12 14 16 18
    Console.ReadKey()
End Sub

Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)

    ' Yield even numbers in the range.
    For number As Integer = firstNumber To lastNumber
        If number Mod 2 = 0 Then
            Yield number
        End If
    Next
End Function

创建集合类

在下面的示例中,DaysOfTheWeek类实现了IEnumerable接口,该接口要求有GetEnumerator方法。 编译器隐式调用 GetEnumerator 方法,该方法返回一个 IEnumerator

该方法 GetEnumerator 使用 Yield 语句一次返回一个字符串,并且函数声明中包含修饰符 Iterator

Sub Main()
    Dim days As New DaysOfTheWeek()
    For Each day As String In days
        Console.Write(day & " ")
    Next
    ' Output: Sun Mon Tue Wed Thu Fri Sat
    Console.ReadKey()
End Sub

Private Class DaysOfTheWeek
    Implements IEnumerable

    Public days =
        New String() {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}

    Public Iterator Function GetEnumerator() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        ' Yield each day of the week.
        For i As Integer = 0 To days.Length - 1
            Yield days(i)
        Next
    End Function
End Class

以下示例创建一个 Zoo 包含动物集合的类。

For Each引用类实例 (theZoo) 的语句隐式调用GetEnumerator该方法。 引用 For EachBirds 属性的 Mammals 语句使用 AnimalsForType 命名迭代器方法。

Sub Main()
    Dim theZoo As New Zoo()

    theZoo.AddMammal("Whale")
    theZoo.AddMammal("Rhinoceros")
    theZoo.AddBird("Penguin")
    theZoo.AddBird("Warbler")

    For Each name As String In theZoo
        Console.Write(name & " ")
    Next
    Console.WriteLine()
    ' Output: Whale Rhinoceros Penguin Warbler

    For Each name As String In theZoo.Birds
        Console.Write(name & " ")
    Next
    Console.WriteLine()
    ' Output: Penguin Warbler

    For Each name As String In theZoo.Mammals
        Console.Write(name & " ")
    Next
    Console.WriteLine()
    ' Output: Whale Rhinoceros

    Console.ReadKey()
End Sub

Public Class Zoo
    Implements IEnumerable

    ' Private members.
    Private animals As New List(Of Animal)

    ' Public methods.
    Public Sub AddMammal(ByVal name As String)
        animals.Add(New Animal With {.Name = name, .Type = Animal.TypeEnum.Mammal})
    End Sub

    Public Sub AddBird(ByVal name As String)
        animals.Add(New Animal With {.Name = name, .Type = Animal.TypeEnum.Bird})
    End Sub

    Public Iterator Function GetEnumerator() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        For Each theAnimal As Animal In animals
            Yield theAnimal.Name
        Next
    End Function

    ' Public members.
    Public ReadOnly Property Mammals As IEnumerable
        Get
            Return AnimalsForType(Animal.TypeEnum.Mammal)
        End Get
    End Property

    Public ReadOnly Property Birds As IEnumerable
        Get
            Return AnimalsForType(Animal.TypeEnum.Bird)
        End Get
    End Property

    ' Private methods.
    Private Iterator Function AnimalsForType( _
    ByVal type As Animal.TypeEnum) As IEnumerable
        For Each theAnimal As Animal In animals
            If (theAnimal.Type = type) Then
                Yield theAnimal.Name
            End If
        Next
    End Function

    ' Private class.
    Private Class Animal
        Public Enum TypeEnum
            Bird
            Mammal
        End Enum

        Public Property Name As String
        Public Property Type As TypeEnum
    End Class
End Class

Try 块

Visual Basic 允许在 Yield 语句存在于 Try 块中。 具有Try语句的Yield块可以拥有Catch块,也可以拥有Finally块。

以下示例包括迭代器函数中的TryCatchFinally块。 迭代器函数中的 Finally 块在 For Each 迭代结束之前执行。

Sub Main()
    For Each number As Integer In Test()
        Console.WriteLine(number)
    Next
    Console.WriteLine("For Each is done.")

    ' Output:
    '  3
    '  4
    '  Something happened. Yields are done.
    '  Finally is called.
    '  For Each is done.
    Console.ReadKey()
End Sub

Private Iterator Function Test() As IEnumerable(Of Integer)
    Try
        Yield 3
        Yield 4
        Throw New Exception("Something happened. Yields are done.")
        Yield 5
        Yield 6
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    Finally
        Console.WriteLine("Finally is called.")
    End Try
End Function

语句Yield不能位于Catch块或Finally块内。

如果 For Each 主体(而不是迭代器方法)引发异常,则不会执行迭代器函数中的 Catch 块,但会执行迭代器函数中的 Finally 块。 Catch迭代器函数内的块只捕获迭代器函数内发生的异常。

匿名方法

在 Visual Basic 中,匿名函数可以是迭代器函数。 下面的示例对此进行了演示。

Dim iterateSequence = Iterator Function() _
                      As IEnumerable(Of Integer)
                          Yield 1
                          Yield 2
                      End Function

For Each number As Integer In iterateSequence()
    Console.Write(number & " ")
Next
' Output: 1 2
Console.ReadKey()

以下示例具有验证参数的非迭代器方法。 该方法返回描述集合元素的匿名迭代器的结果。

Sub Main()
    For Each number As Integer In GetSequence(5, 10)
        Console.Write(number & " ")
    Next
    ' Output: 5 6 7 8 9 10
    Console.ReadKey()
End Sub

Public Function GetSequence(ByVal low As Integer, ByVal high As Integer) _
As IEnumerable
    ' Validate the arguments.
    If low < 1 Then
        Throw New ArgumentException("low is too low")
    End If
    If high > 140 Then
        Throw New ArgumentException("high is too high")
    End If

    ' Return an anonymous iterator function.
    Dim iterateSequence = Iterator Function() As IEnumerable
                              For index = low To high
                                  Yield index
                              Next
                          End Function
    Return iterateSequence()
End Function

如果验证位于迭代器函数内部,则在正文的第一次迭代 For Each 开始之前,无法执行验证。

将迭代器与泛型列表配合使用

在以下示例中, Stack(Of T) 泛型类实现 IEnumerable<T> 泛型接口。 该方法 Push 将值分配给类型的 T数组。 该方法 GetEnumerator 使用 Yield 语句返回数组值。

除了泛型 GetEnumerator 方法,还必须实现非泛型 GetEnumerator 方法。 这是因为 IEnumerable<T> 继承自 IEnumerable. 非泛型实现遵从泛型实现的规则。

该示例使用命名迭代器来支持遍历同一数据收集的各种方式。 这些命名迭代器包括 TopToBottomBottomToTop 属性,以及 TopN 方法。

属性 BottomToTop 声明包括 Iterator 关键字。

Sub Main()
    Dim theStack As New Stack(Of Integer)

    ' Add items to the stack.
    For number As Integer = 0 To 9
        theStack.Push(number)
    Next

    ' Retrieve items from the stack.
    ' For Each is allowed because theStack implements
    ' IEnumerable(Of Integer).
    For Each number As Integer In theStack
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 9 8 7 6 5 4 3 2 1 0

    ' For Each is allowed, because theStack.TopToBottom
    ' returns IEnumerable(Of Integer).
    For Each number As Integer In theStack.TopToBottom
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 9 8 7 6 5 4 3 2 1 0

    For Each number As Integer In theStack.BottomToTop
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 0 1 2 3 4 5 6 7 8 9

    For Each number As Integer In theStack.TopN(7)
        Console.Write("{0} ", number)
    Next
    Console.WriteLine()
    ' Output: 9 8 7 6 5 4 3

    Console.ReadKey()
End Sub

Public Class Stack(Of T)
    Implements IEnumerable(Of T)

    Private values As T() = New T(99) {}
    Private top As Integer = 0

    Public Sub Push(ByVal t As T)
        values(top) = t
        top = top + 1
    End Sub

    Public Function Pop() As T
        top = top - 1
        Return values(top)
    End Function

    ' This function implements the GetEnumerator method. It allows
    ' an instance of the class to be used in a For Each statement.
    Public Iterator Function GetEnumerator() As IEnumerator(Of T) _
        Implements IEnumerable(Of T).GetEnumerator

        For index As Integer = top - 1 To 0 Step -1
            Yield values(index)
        Next
    End Function

    Public Iterator Function GetEnumerator1() As IEnumerator _
        Implements IEnumerable.GetEnumerator

        Yield GetEnumerator()
    End Function

    Public ReadOnly Property TopToBottom() As IEnumerable(Of T)
        Get
            Return Me
        End Get
    End Property

    Public ReadOnly Iterator Property BottomToTop As IEnumerable(Of T)
        Get
            For index As Integer = 0 To top - 1
                Yield values(index)
            Next
        End Get
    End Property

    Public Iterator Function TopN(ByVal itemsFromTop As Integer) _
        As IEnumerable(Of T)

        ' Return less than itemsFromTop if necessary.
        Dim startIndex As Integer =
            If(itemsFromTop >= top, 0, top - itemsFromTop)

        For index As Integer = top - 1 To startIndex Step -1
            Yield values(index)
        Next
    End Function
End Class

语法信息

迭代器可用作一种方法,或一个 get 访问器。 迭代器不能在事件、实例构造函数、静态构造函数或静态析构函数中发生。

从语句中的 Yield 表达式类型到迭代器的返回类型,隐式转换必须存在。

在 Visual Basic 中,迭代器方法不能有任何 ByRef 参数。

在 Visual Basic 中,“Yield”不是保留字,仅在Iterator方法或get访问器中使用时才具有特殊意义。

技术实现

尽管将迭代器编写为方法,但编译器会将它转换为实际上为状态机的嵌套类。 只要客户端代码中的 For Each...Next 循环继续,此类就会跟踪迭代器的位置。

若要查看编译器的作用,可以使用 Ildasm.exe 工具查看为迭代器方法生成的公共中间语言代码。

结构创建迭代器时,无需实现整个 IEnumerator 接口。 当编译器检测到迭代器时,它会自动生成CurrentMoveNext接口中的DisposeIEnumeratorIEnumerator<T>方法。

For Each…Next 循环(或对 IEnumerator.MoveNext 的直接调用)的每次后续迭代中,下一个迭代器代码体都会在上一个 Yield 语句之后恢复。 然后,它会继续执行下一个 Yield 语句,直到到达迭代器正文的末尾,或者遇到 Exit FunctionReturn 语句。

迭代器不支持该方法 IEnumerator.Reset 。 若要重新从头开始迭代,必须获取新的迭代器。

有关详细信息,请参阅 Visual Basic 语言规范

使用迭代器

当需要使用复杂代码填充列表序列时,迭代器使你能够保持循环的 For Each 简单性。 若要执行以下操作,这会很有帮助:

  • 在第一次 For Each 循环迭代后修改列表序列。

  • 避免在For Each循环的第一次迭代之前完全加载大型列表。 一个示例是用于加载一批表格行的分页提取。 另一个示例是在 EnumerateFiles .NET Framework 中实现迭代器的方法。

  • 在迭代器中封装列表的构建过程。 在迭代器方法中,可以生成列表,然后在循环中生成每个结果。

另请参阅