共用方式為


GetEnumerator 方法 (Collection 物件)

更新:2007 年 11 月

傳回對列舉值物件的參考,這個物件是用來反覆查看Collection 物件 (Visual Basic)

 Public Function GetEnumerator() As IEnumerator

備註

For Each...Next 陳述式 (Visual Basic) 會呼叫 GetEnumerator,以取得支援逐一查看集合項目的列舉值物件。一般而言,使用 For Each...Next 迴圈即可往返於集合或陣列,而不需要明確呼叫 GetEnumerator。

如果您需要對反覆運算進行比 For Each...Next 陳述式所提供之更為嚴密的控制,則可使用 GetEnumerator 方法來執行自訂的走訪。下列是一些可能需做這類處理的情況。

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

  • 您可能會因為各種理由,而想略過一或多個項目。

  • 您可能需在走訪中途變更集合項目。在此情況下,因為前一個列舉值物件已經失效,所以您必須取得新的列舉值物件。

範例

下列範例會顯示如何使用 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 會建構和傳回列舉值物件,這會實作 System.Collections 命名空間的 IEnumerator 介面。列舉值物件會公開 Current 屬性以及 MoveNextReset 方法。如需詳細資訊,請參閱 For Each...Next 陳述式 (Visual Basic)

需求

命名空間:Microsoft.VisualBasic

**模組:**Collection

**組件:**Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)

請參閱

參考

Collection 物件 (Visual Basic)