Collection.GetEnumerator 方法


傳回逐一查看集合的列舉值。Returns an enumerator that iterates through the collection.

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


可用來逐一查看集合的列舉值。An enumerator that can be used to iterate through the collection.


下列範例顯示如何使用 GetEnumerator 來抓取 Collection 物件的所有專案。The following example shows how to use GetEnumerator to retrieve all the elements of a Collection object.

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

GetEnumerator 會建立並傳回列舉值物件,它會實作為 System.Collections 命名空間的 IEnumerator 介面。GetEnumerator constructs and returns an enumerator object, which implements the IEnumerator interface of the System.Collections namespace. 列舉值物件會公開 Current 屬性和 MoveNextReset 方法。The enumerator object exposes the Current property and the MoveNext and Reset methods. 如需詳細資訊,請參閱For Each .。。下一個語句For more information, see For Each...Next Statement.


For Each .。。下一個語句會呼叫 GetEnumerator 來取得列舉值物件,以支援在集合元素上反覆運算。The For Each...Next Statement calls GetEnumerator to obtain an enumerator object to support iteration over a collection's elements. 一般來說,您可以使用 For Each...Next 迴圈來流覽集合或陣列,而不需要明確地呼叫 GetEnumeratorNormally, you use a For Each...Next loop to traverse a collection or array, and you do not need to call GetEnumerator explicitly.

如果您需要比 For Each...Next 語句所提供的反復專案更進一步控制,您可以使用 GetEnumerator 方法來執行自訂的遍歷。If you need closer control over the iteration than the For Each...Next statements provide, you can use the GetEnumerator method to perform a customized traversal. 以下是您可能需要執行這項操作的一些情況。The following are some cases in which you might need to do this.

  • 您可能想要回到集合的開頭,然後在完成之前再次開始反復專案。You might want to return to the beginning of the collection and start the iteration again before it is finished.

  • 基於各種原因,您可能會想要跳過一或多個元素。You might want to skip over one or more elements for a variety of reasons.

  • 您可能需要在「遍歷」中間變更集合的元素。You might need to change the elements of the collection in the middle of a traversal. 在此情況下,您必須取得新的列舉值物件,因為上一個是不正確。In this case you must obtain a new enumerator object because the previous one is invalidated.