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 公開 屬性和 MoveNextReset 方法。 如需詳細資訊,請參閱 For Each...Next 陳述式

備註

每個...Next 語句會呼叫 GetEnumerator ,以取得列舉值物件,以支援對集合專案的反覆專案。 一般而言,您會使用 For Each...Next 循環來周遊集合或陣列,而且您不需要明確呼叫 GetEnumerator

如果您需要比 ...Next 語句所提供的更仔細控制反覆專案For Each,您可以使用 GetEnumerator 方法來執行自定義周遊。 以下是您可能需要執行這項操作的一些案例。

  • 您可能想要回到集合的開頭,並在完成之前再次開始反覆專案。

  • 基於各種原因,您可能會想要略過一或多個元素。

  • 您可能需要在周遊中間變更集合的專案。 在此情況下,您必須取得新的列舉值對象,因為前一個列舉值無效。

適用於