通过


Collection.GetEnumerator 方法

定义

返回循环访问集合的枚举器。

public:
 System::Collections::IEnumerator ^ GetEnumerator();
public System.Collections.IEnumerator GetEnumerator();
member this.GetEnumerator : unit -> System.Collections.IEnumerator
Public Function GetEnumerator () As IEnumerator

返回

可用于循环访问集合的枚举器。

示例

以下示例演示如何用于 GetEnumerator 检索对象的所有元素 Collection

Dim customers As New Collection
' Insert code to add elements to the customers collection.
Dim custEnum As IEnumerator = customers.GetEnumerator()
custEnum.Reset()
Dim thisCustomer As Object
While custEnum.MoveNext()
    thisCustomer = custEnum.Current()
    ' Insert code to process this element of the collection.
End While

GetEnumerator 构造并返回一个枚举器对象,该对象实现 IEnumerator 命名空间的 System.Collections 接口。 枚举器对象公开 Current 属性和 MoveNext 方法和 Reset 方法。 有关详细信息,请参阅 For Each...Next 语句

注解

For Each...Next 语句调用GetEnumerator以获取枚举器对象以支持对集合元素的迭代。 通常,使用 For Each...Next 循环遍历集合或数组,并且不需要显式调用 GetEnumerator

如果需要比 ...Next 语句提供的更紧密地控制迭代For Each,则可以使用GetEnumerator该方法执行自定义遍历。 下面是可能需要执行此操作的一些情况。

  • 你可能想要返回到集合的开头,并在迭代完成之前重新开始迭代。

  • 出于各种原因,可能需要跳过一个或多个元素。

  • 可能需要在遍历中间更改集合的元素。 在这种情况下,必须获取新的枚举器对象,因为前一个枚举器对象无效。

适用于