集合 (Visual Basic)Collections (Visual Basic)

在許多應用程式中,您想要建立和管理相關物件的群組。For many applications, you want to create and manage groups of related objects. 有兩種方式可以群組物件:建立物件的陣列和建立物件的集合。There are two ways to group objects: by creating arrays of objects, and by creating collections of objects.

陣列是最適用於建立和處理固定數目的強類型物件。Arrays are most useful for creating and working with a fixed number of strongly-typed objects. 如需陣列的資訊,請參閱陣列For information about arrays, see Arrays.

集合會提供較具彈性的方式來使用物件群組。Collections provide a more flexible way to work with groups of objects. 與陣列不同的是,您使用的物件群組可依程式變更的需要來動態增減。Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change. 對於某些集合,您可以將鍵值指派給您放入集合的任何物件,讓您可以藉由使用鍵值快速擷取物件。For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key.

集合是類別,因此您必須在將項目加入該集合之前,宣告類別的執行個體。A collection is a class, so you must declare an instance of the class before you can add elements to that collection.

如果集合包含只有一個資料類型的項目,則可使用 System.Collections.Generic 命名空間內的其中一個類別。If your collection contains elements of only one data type, you can use one of the classes in the System.Collections.Generic namespace. 泛型集合會強制類型安全,如此就不會加入其他資料類型。A generic collection enforces type safety so that no other data type can be added to it. 當您從泛型集合中擷取項目時,並不需要判斷其資料類型或將其轉換。When you retrieve an element from a generic collection, you do not have to determine its data type or convert it.

注意

如需本主題的範例,包括匯入陳述式System.Collections.GenericSystem.Linq命名空間。For the examples in this topic, include Imports statements for the System.Collections.Generic and System.Linq namespaces.

使用簡單的集合Using a Simple Collection

本節中的範例使用泛型 List<T> 類別,能夠讓您使用強型別物件清單。The examples in this section use the generic List<T> class, which enables you to work with a strongly typed list of objects.

下列範例會建立字串清單,並再逐一查看字串使用每個...下一步陳述式。The following example creates a list of strings and then iterates through the strings by using a For Each…Next statement.

' Create a list of strings.
Dim salmons As New List(Of String)
salmons.Add("chinook")
salmons.Add("coho")
salmons.Add("pink")
salmons.Add("sockeye")

' Iterate through the list.
For Each salmon As String In salmons
    Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye

如果預先知道集合的內容,即可使用「集合初始設定式」來初始化集合。If the contents of a collection are known in advance, you can use a collection initializer to initialize the collection. 如需詳細資訊,請參閱集合初始設定式For more information, see Collection Initializers.

下列範例與前一個範例相同,但有一點除外,就是集合初始設定式是用來將項目加入集合中。The following example is the same as the previous example, except a collection initializer is used to add elements to the collection.

' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
    {"chinook", "coho", "pink", "sockeye"}

For Each salmon As String In salmons
    Console.Write(salmon & " ")
Next
'Output: chinook coho pink sockeye

您可以使用For...下一步陳述式來取代For Each陳述式來逐一查看集合。You can use a For…Next statement instead of a For Each statement to iterate through a collection. 您可以藉由依索引位置存取集合項目來完成這項作業。You accomplish this by accessing the collection elements by the index position. 項目的索引以 0 開始,並以項目計數減 1 結束。The index of the elements starts at 0 and ends at the element count minus 1.

下列範例會使用 For…Next 來逐一查看集合的項目,而不是使用 For EachThe following example iterates through the elements of a collection by using For…Next instead of For Each.

Dim salmons As New List(Of String) From
    {"chinook", "coho", "pink", "sockeye"}

For index = 0 To salmons.Count - 1
    Console.Write(salmons(index) & " ")
Next
'Output: chinook coho pink sockeye

下列範例透過指定要移除的物件,從集合中移除項目。The following example removes an element from the collection by specifying the object to remove.

' Create a list of strings by using a
' collection initializer.
Dim salmons As New List(Of String) From
    {"chinook", "coho", "pink", "sockeye"}

' Remove an element in the list by specifying
' the object.
salmons.Remove("coho")

For Each salmon As String In salmons
    Console.Write(salmon & " ")
Next
'Output: chinook pink sockeye

下列範例會移除泛型清單中的項目。The following example removes elements from a generic list. 而不是For Each陳述式, For...下一步以遞減順序反覆運算的陳述式。Instead of a For Each statement, a For…Next statement that iterates in descending order is used. 這是因為 RemoveAt 方法導致在已移除之項目後面的項目具有較低的索引值。This is because the RemoveAt method causes elements after a removed element to have a lower index value.

Dim numbers As New List(Of Integer) From
    {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

' Remove odd numbers.
For index As Integer = numbers.Count - 1 To 0 Step -1
    If numbers(index) Mod 2 = 1 Then
        ' Remove the element by specifying
        ' the zero-based index in the list.
        numbers.RemoveAt(index)
    End If
Next

' Iterate through the list.
' A lambda expression is placed in the ForEach method
' of the List(T) object.
numbers.ForEach(
    Sub(number) Console.Write(number & " "))
' Output: 0 2 4 6 8

如需 List<T> 中的項目類型,您也可以定義自己的類別。For the type of elements in the List<T>, you can also define your own class. 在下列範例中,List<T> 使用的 Galaxy 類別是在程式碼中定義的。In the following example, the Galaxy class that is used by the List<T> is defined in the code.

Private Sub IterateThroughList()
    Dim theGalaxies As New List(Of Galaxy) From
        {
            New Galaxy With {.Name = "Tadpole", .MegaLightYears = 400},
            New Galaxy With {.Name = "Pinwheel", .MegaLightYears = 25},
            New Galaxy With {.Name = "Milky Way", .MegaLightYears = 0},
            New Galaxy With {.Name = "Andromeda", .MegaLightYears = 3}
        }

    For Each theGalaxy In theGalaxies
        With theGalaxy
            Console.WriteLine(.Name & "  " & .MegaLightYears)
        End With
    Next

    ' Output:
    '  Tadpole  400
    '  Pinwheel  25
    '  Milky Way  0
    '  Andromeda  3
End Sub

Public Class Galaxy
    Public Property Name As String
    Public Property MegaLightYears As Integer
End Class

集合的種類Kinds of Collections

.NET Framework 會提供很多常見的集合。Many common collections are provided by the .NET Framework. 各個類型的集合都是針對特定用途來設計。Each type of collection is designed for a specific purpose.

下列集合類別的群組將在本節介紹:Some of the common collection classes are described in this section:

System.Collections.Generic 類別System.Collections.Generic Classes

藉由使用 System.Collections.Generic 命名空間的其中一個類別,您可以建立泛型集合。You can create a generic collection by using one of the classes in the System.Collections.Generic namespace. 當集合中每個項目的資料類型相同時,泛型集合就相當有用。A generic collection is useful when every item in the collection has the same data type. 泛型集合會透過只允許加入所需資料類型的方式,強制使用強式類型。A generic collection enforces strong typing by allowing only the desired data type to be added.

下表列出 System.Collections.Generic 命名空間的一些常用類別:The following table lists some of the frequently used classes of the System.Collections.Generic namespace:

類別Class 描述Description
Dictionary<TKey,TValue> 表示根據索引鍵所整理的索引鍵/值組集合。Represents a collection of key/value pairs that are organized based on the key.
List<T> 表示可以依照索引存取的物件清單。Represents a list of objects that can be accessed by index. 提供搜尋、排序和修改清單的方法。Provides methods to search, sort, and modify lists.
Queue<T> 表示物件的先進先出 (FIFO) 集合。Represents a first in, first out (FIFO) collection of objects.
SortedList<TKey,TValue> 代表根據關聯的 IComparer<T> 實作,依索引鍵所排序的索引鍵/值組集合。Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.
Stack<T> 表示物件的後進先出 (LIFO) 集合。Represents a last in, first out (LIFO) collection of objects.

如需其他資訊,請參閱常用的集合類型選取集合類別System.Collections.GenericFor additional information, see Commonly Used Collection Types, Selecting a Collection Class, and System.Collections.Generic.

System.Collections.Concurrent 類別System.Collections.Concurrent Classes

在 .NET Framework 4 或更新版本中,System.Collections.Concurrent 命名空間中的集合提供了有效率的安全執行緒作業,可從多個執行緒存取集合項目。In the .NET Framework 4 or newer, the collections in the System.Collections.Concurrent namespace provide efficient thread-safe operations for accessing collection items from multiple threads.

每當有多個執行緒同時存取集合時,應該使用 System.Collections.Concurrent 命名空間中的類別來代替 System.Collections.GenericSystem.Collections 命名空間中的對應類型。The classes in the System.Collections.Concurrent namespace should be used instead of the corresponding types in the System.Collections.Generic and System.Collections namespaces whenever multiple threads are accessing the collection concurrently. 如需詳細資訊,請參閱安全執行緒集合System.Collections.ConcurrentFor more information, see Thread-Safe Collections and System.Collections.Concurrent.

System.Collections.Concurrent 命名空間中包含一些類別,包括 BlockingCollection<T>ConcurrentDictionary<TKey,TValue>ConcurrentQueue<T>ConcurrentStack<T>Some classes included in the System.Collections.Concurrent namespace are BlockingCollection<T>, ConcurrentDictionary<TKey,TValue>, ConcurrentQueue<T>, and ConcurrentStack<T>.

System.Collections 類別System.Collections Classes

System.Collections 命名空間中的類別不會將項目儲存為特別類型物件,而是會儲存為 Object 類型的物件。The classes in the System.Collections namespace do not store elements as specifically typed objects, but as objects of type Object.

可能的話,您應該使用 System.Collections.Generic 命名空間或 System.Collections.Concurrent 命名空間中的泛型集合,而非 System.Collections 命名空間中的傳統類型。Whenever possible, you should use the generic collections in the System.Collections.Generic namespace or the System.Collections.Concurrent namespace instead of the legacy types in the System.Collections namespace.

下表列出 System.Collections 命名空間的一些常用類別:The following table lists some of the frequently used classes in the System.Collections namespace:

類別Class 描述Description
ArrayList 代表會視需要動態增加大小的物件陣列。Represents an array of objects whose size is dynamically increased as required.
Hashtable 代表根據索引鍵的雜湊程式碼,所整理的索引鍵/值組集合。Represents a collection of key/value pairs that are organized based on the hash code of the key.
Queue 表示物件的先進先出 (FIFO) 集合。Represents a first in, first out (FIFO) collection of objects.
Stack 表示物件的後進先出 (LIFO) 集合。Represents a last in, first out (LIFO) collection of objects.

System.Collections.Specialized 命名空間會提供特製化類型和強型別集合類別,例如只有字串的集合,以及連結串列和 Hybrid 字典。The System.Collections.Specialized namespace provides specialized and strongly typed collection classes, such as string-only collections and linked-list and hybrid dictionaries.

Visual Basic Collection 類別Visual Basic Collection Class

使用數值索引或 String 索引鍵,您就可以使用 Visual Basic Collection 類別來存取集合項目。You can use the Visual Basic Collection class to access a collection item by using either a numeric index or a String key. 不論是否指定索引鍵,您都可以在集合物件中加入項目。You can add items to a collection object either with or without specifying a key. 如果加入不具索引鍵的項目,則必須使用它的數值索引加以存取。If you add an item without a key, you must use its numeric index to access it.

Visual Basic Collection 類別會將其所有項目儲存為類型 Object,因此可以加入屬於任何資料類型的項目。The Visual Basic Collection class stores all its elements as type Object, so you can add an item of any data type. 無法確定加入的資料類型皆適當無誤。There is no safeguard against inappropriate data types being added.

當您使用 Visual Basic Collection 類別時,集合中第一個項目的索引為 1。When you use the Visual Basic Collection class, the first item in a collection has an index of 1. 這與 .NET Framework 集合類別不同,後者的起始索引為 0。This differs from the .NET Framework collection classes, for which the starting index is 0.

可能的話,請盡量使用 System.Collections.GenericSystem.Collections.Concurrent 命名空間中的泛型集合,而非 Visual Basic Collection 類別。Whenever possible, you should use the generic collections in the System.Collections.Generic namespace or the System.Collections.Concurrent namespace instead of the Visual Basic Collection class.

如需詳細資訊,請參閱 CollectionFor more information, see Collection.

實作索引鍵/值組集合。Implementing a Collection of Key/Value Pairs

Dictionary<TKey,TValue> 泛型集合可讓您使用每個項目的索引鍵來存取集合中的項目。The Dictionary<TKey,TValue> generic collection enables you to access to elements in a collection by using the key of each element. 加入字典中的每一個項目都是由值及其關聯索引鍵所組成。Each addition to the dictionary consists of a value and its associated key. 使用其索引鍵擷取值的速度非常快,因為 Dictionary 類別是實作為雜湊表。Retrieving a value by using its key is fast because the Dictionary class is implemented as a hash table.

下列範例會使用 For Each 陳述式建立 Dictionary 集合並逐一查看字典。The following example creates a Dictionary collection and iterates through the dictionary by using a For Each statement.

Private Sub IterateThroughDictionary()
    Dim elements As Dictionary(Of String, Element) = BuildDictionary()

    For Each kvp As KeyValuePair(Of String, Element) In elements
        Dim theElement As Element = kvp.Value

        Console.WriteLine("key: " & kvp.Key)
        With theElement
            Console.WriteLine("values: " & .Symbol & " " &
                .Name & " " & .AtomicNumber)
        End With
    Next
End Sub

Private Function BuildDictionary() As Dictionary(Of String, Element)
    Dim elements As New Dictionary(Of String, Element)

    AddToDictionary(elements, "K", "Potassium", 19)
    AddToDictionary(elements, "Ca", "Calcium", 20)
    AddToDictionary(elements, "Sc", "Scandium", 21)
    AddToDictionary(elements, "Ti", "Titanium", 22)

    Return elements
End Function

Private Sub AddToDictionary(ByVal elements As Dictionary(Of String, Element),
ByVal symbol As String, ByVal name As String, ByVal atomicNumber As Integer)
    Dim theElement As New Element

    theElement.Symbol = symbol
    theElement.Name = name
    theElement.AtomicNumber = atomicNumber

    elements.Add(Key:=theElement.Symbol, value:=theElement)
End Sub

Public Class Element
    Public Property Symbol As String
    Public Property Name As String
    Public Property AtomicNumber As Integer
End Class

若要改為使用集合初始設定式建置 Dictionary 集合,您可以使用下列方法取代 BuildDictionaryAddToDictionary 方法。To instead use a collection initializer to build the Dictionary collection, you can replace the BuildDictionary and AddToDictionary methods with the following method.

Private Function BuildDictionary2() As Dictionary(Of String, Element)
    Return New Dictionary(Of String, Element) From
        {
            {"K", New Element With
                {.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
            {"Ca", New Element With
                {.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
            {"Sc", New Element With
                {.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
            {"Ti", New Element With
                {.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
        }
End Function

下列範例會使用 ContainsKey 方法和 DictionaryItem[TKey] 屬性來依索引鍵快速尋找項目。The following example uses the ContainsKey method and the Item[TKey] property of Dictionary to quickly find an item by key. Item屬性可讓您存取中的項目elements使用集合elements(symbol)Visual Basic 中的程式碼。The Item property enables you to access an item in the elements collection by using the elements(symbol) code in Visual Basic.

Private Sub FindInDictionary(ByVal symbol As String)
    Dim elements As Dictionary(Of String, Element) = BuildDictionary()

    If elements.ContainsKey(symbol) = False Then
        Console.WriteLine(symbol & " not found")
    Else
        Dim theElement = elements(symbol)
        Console.WriteLine("found: " & theElement.Name)
    End If
End Sub

下列範例會使用 TryGetValue 方法依索引鍵來快速尋找項目。The following example instead uses the TryGetValue method quickly find an item by key.

Private Sub FindInDictionary2(ByVal symbol As String)
    Dim elements As Dictionary(Of String, Element) = BuildDictionary()

    Dim theElement As Element = Nothing
    If elements.TryGetValue(symbol, theElement) = False Then
        Console.WriteLine(symbol & " not found")
    Else
        Console.WriteLine("found: " & theElement.Name)
    End If
End Sub

使用 LINQ 存取集合Using LINQ to Access a Collection

LINQ (Language-Integrated Query (LINQ)) 可用來存取集合。LINQ (Language-Integrated Query) can be used to access collections. LINQ 查詢提供篩選、排序和分組功能。LINQ queries provide filtering, ordering, and grouping capabilities. 如需詳細資訊,請參閱 < Getting Started with Visual Basic 中的 LINQFor more information, see Getting Started with LINQ in Visual Basic.

下列範例會對泛型 List 執行 LINQ 查詢。The following example runs a LINQ query against a generic List. LINQ 查詢會傳回包含結果的不同集合。The LINQ query returns a different collection that contains the results.

Private Sub ShowLINQ()
    Dim elements As List(Of Element) = BuildList()

    ' LINQ Query.
    Dim subset = From theElement In elements
                  Where theElement.AtomicNumber < 22
                  Order By theElement.Name

    For Each theElement In subset
        Console.WriteLine(theElement.Name & " " & theElement.AtomicNumber)
    Next

    ' Output:
    '  Calcium 20
    '  Potassium 19
    '  Scandium 21
End Sub

Private Function BuildList() As List(Of Element)
    Return New List(Of Element) From
        {
            {New Element With
                {.Symbol = "K", .Name = "Potassium", .AtomicNumber = 19}},
            {New Element With
                {.Symbol = "Ca", .Name = "Calcium", .AtomicNumber = 20}},
            {New Element With
                {.Symbol = "Sc", .Name = "Scandium", .AtomicNumber = 21}},
            {New Element With
                {.Symbol = "Ti", .Name = "Titanium", .AtomicNumber = 22}}
        }
End Function

Public Class Element
    Public Property Symbol As String
    Public Property Name As String
    Public Property AtomicNumber As Integer
End Class

為集合排序Sorting a Collection

下列範例說明排序集合的程序。The following example illustrates a procedure for sorting a collection. 此範例排序儲存在 List<T> 中的 Car 類別執行個體。The example sorts instances of the Car class that are stored in a List<T>. Car 類別實作 IComparable<T> 介面,而這個介面要求實作 CompareTo 方法。The Car class implements the IComparable<T> interface, which requires that the CompareTo method be implemented.

每次對 CompareTo 方法的呼叫都會進行用於排序的單一比較。Each call to the CompareTo method makes a single comparison that is used for sorting. 當目前物件和另一個物件比較時,在 CompareTo 方法中的使用者撰寫程式碼會傳回值。User-written code in the CompareTo method returns a value for each comparison of the current object with another object. 如果目前物件比另一個物件小則傳回的值小於零,如果目前物件比另一個物件大則傳回的值大於零,如果它們相等則傳回零。The value returned is less than zero if the current object is less than the other object, greater than zero if the current object is greater than the other object, and zero if they are equal. 這可讓您以程式碼定義大於、小於、等於的準則。This enables you to define in code the criteria for greater than, less than, and equal.

ListCars 方法中,cars.Sort() 陳述式會排序清單。In the ListCars method, the cars.Sort() statement sorts the list. List<T>Sort 方法的這個呼叫,會導致 CompareTo 方法對 ListCar 物件自動呼叫。This call to the Sort method of the List<T> causes the CompareTo method to be called automatically for the Car objects in the List.

Public Sub ListCars()

    ' Create some new cars.
    Dim cars As New List(Of Car) From
    {
        New Car With {.Name = "car1", .Color = "blue", .Speed = 20},
        New Car With {.Name = "car2", .Color = "red", .Speed = 50},
        New Car With {.Name = "car3", .Color = "green", .Speed = 10},
        New Car With {.Name = "car4", .Color = "blue", .Speed = 50},
        New Car With {.Name = "car5", .Color = "blue", .Speed = 30},
        New Car With {.Name = "car6", .Color = "red", .Speed = 60},
        New Car With {.Name = "car7", .Color = "green", .Speed = 50}
    }

    ' Sort the cars by color alphabetically, and then by speed
    ' in descending order.
    cars.Sort()

    ' View all of the cars.
    For Each thisCar As Car In cars
        Console.Write(thisCar.Color.PadRight(5) & " ")
        Console.Write(thisCar.Speed.ToString & " ")
        Console.Write(thisCar.Name)
        Console.WriteLine()
    Next

    ' Output:
    '  blue  50 car4
    '  blue  30 car5
    '  blue  20 car1
    '  green 50 car7
    '  green 10 car3
    '  red   60 car6
    '  red   50 car2
End Sub

Public Class Car
    Implements IComparable(Of Car)

    Public Property Name As String
    Public Property Speed As Integer
    Public Property Color As String

    Public Function CompareTo(ByVal other As Car) As Integer _
        Implements System.IComparable(Of Car).CompareTo
        ' A call to this method makes a single comparison that is
        ' used for sorting.

        ' Determine the relative order of the objects being compared.
        ' Sort by color alphabetically, and then by speed in
        ' descending order.

        ' Compare the colors.
        Dim compare As Integer
        compare = String.Compare(Me.Color, other.Color, True)

        ' If the colors are the same, compare the speeds.
        If compare = 0 Then
            compare = Me.Speed.CompareTo(other.Speed)

            ' Use descending order for speed.
            compare = -compare
        End If

        Return compare
    End Function
End Class

定義自訂集合Defining a Custom Collection

您可以透過實作 IEnumerable<T>IEnumerable 介面來定義集合。You can define a collection by implementing the IEnumerable<T> or IEnumerable interface. 如需詳細資訊,請參閱列舉集合For additional information, see Enumerating a Collection.

雖然您可以定義自訂集合,但是使用包含在 .NET Framework 中的集合 (本主題稍早在集合的種類中所述) 通常會比較好。Although you can define a custom collection, it is usually better to instead use the collections that are included in the .NET Framework, which are described in Kinds of Collections earlier in this topic.

下列範例會定義名為 AllColors 的自訂集合類別。The following example defines a custom collection class named AllColors. 這個類別實作 IEnumerable 介面,該介面要求實作 GetEnumerator 方法。This class implements the IEnumerable interface, which requires that the GetEnumerator method be implemented.

GetEnumerator 方法會傳回 ColorEnumerator 類別的執行個體。The GetEnumerator method returns an instance of the ColorEnumerator class. ColorEnumerator 實作 IEnumerator 介面,而此介面會要求實作 Current 屬性、MoveNext 方法和 Reset 方法。ColorEnumerator implements the IEnumerator interface, which requires that the Current property, MoveNext method, and Reset method be implemented.

Public Sub ListColors()
    Dim colors As New AllColors()

    For Each theColor As Color In colors
        Console.Write(theColor.Name & " ")
    Next
    Console.WriteLine()
    ' Output: red blue green
End Sub

' Collection class.
Public Class AllColors
    Implements System.Collections.IEnumerable

    Private _colors() As Color =
    {
        New Color With {.Name = "red"},
        New Color With {.Name = "blue"},
        New Color With {.Name = "green"}
    }

    Public Function GetEnumerator() As System.Collections.IEnumerator _
        Implements System.Collections.IEnumerable.GetEnumerator

        Return New ColorEnumerator(_colors)

        ' Instead of creating a custom enumerator, you could
        ' use the GetEnumerator of the array.
        'Return _colors.GetEnumerator
    End Function

    ' Custom enumerator.
    Private Class ColorEnumerator
        Implements System.Collections.IEnumerator

        Private _colors() As Color
        Private _position As Integer = -1

        Public Sub New(ByVal colors() As Color)
            _colors = colors
        End Sub

        Public ReadOnly Property Current() As Object _
            Implements System.Collections.IEnumerator.Current
            Get
                Return _colors(_position)
            End Get
        End Property

        Public Function MoveNext() As Boolean _
            Implements System.Collections.IEnumerator.MoveNext
            _position += 1
            Return (_position < _colors.Length)
        End Function

        Public Sub Reset() Implements System.Collections.IEnumerator.Reset
            _position = -1
        End Sub
    End Class
End Class

' Element class.
Public Class Color
    Public Property Name As String
End Class

迭代器Iterators

「迭代器」是用來在集合上執行自訂反覆項目。An iterator is used to perform a custom iteration over a collection. 迭代器可以是方法或 get 存取子。An iterator can be a method or a get accessor. 迭代器會使用產生陳述式來傳回一次一個集合的每個項目。An iterator uses a Yield statement to return each element of the collection one at a time.

您可以使用呼叫迭代器每個...下一步陳述式。You call an iterator by using a For Each…Next statement. For Each 迴圈的每個反覆項目都會呼叫迭代器。Each iteration of the For Each loop calls the iterator. 在迭代器中到達 Yield 陳述式時,會傳回運算式,並保留程式碼中的目前位置。When a Yield statement is reached in the iterator, an expression is returned, and the current location in code is retained. 下一次呼叫迭代器時,便會從這個位置重新開始執行。Execution is restarted from that location the next time that the iterator is called.

如需詳細資訊,請參閱 < 迭代器 (Visual Basic)For more information, see Iterators (Visual Basic).

下列範例使用了 iterator 方法。The following example uses an iterator method. Iterator 方法具有Yield內的陳述式For...下一步迴圈。The iterator method has a Yield statement that is inside a For…Next loop. ListEvenNumbers 方法中,For Each 陳述式主體的每個反覆項目都會建立對 Iterator 方法的呼叫,這個方法將繼續執行下一個 Yield 陳述式。In the ListEvenNumbers method, each iteration of the For Each statement body creates a call to the iterator method, which proceeds to the next Yield statement.

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

Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As IEnumerable(Of Integer)

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

另請參閱See also