IEnumerator<T> 接口


支持在泛型集合上进行简单迭代。Supports a simple iteration over a generic collection.

generic <typename T>
public interface class IEnumerator : IDisposable, System::Collections::IEnumerator
public interface IEnumerator<out T> : IDisposable, System.Collections.IEnumerator
type IEnumerator<'T> = interface
    interface IDisposable
    interface IEnumerator
Public Interface IEnumerator(Of Out T)
Implements IDisposable, IEnumerator



要枚举的对象的类型。The type of objects to enumerate.

这是协变类型参数。 即,可以使用指定的类型,也可以使用派生程度较高的任何类型。 有关协变和逆变的详细信息,请参阅泛型中的协变和逆变


下面的示例演示自定义对象的集合类的 IEnumerator<T> 接口的实现。The following example shows an implementation of the IEnumerator<T> interface for a collection class of custom objects. 自定义对象是 Box类型的实例,并且集合类是 BoxCollection的。The custom object is an instance of the type Box, and the collection class is BoxCollection. 此代码示例是为 ICollection<T> 接口提供的更大示例的一部分。This code example is part of a larger example provided for the ICollection<T> interface.

// Defines the enumerator for the Boxes collection.
// (Some prefer this class nested in the collection class.)
public class BoxEnumerator : IEnumerator<Box>
    private BoxCollection _collection;
    private int curIndex;
    private Box curBox;

    public BoxEnumerator(BoxCollection collection)
        _collection = collection;
        curIndex = -1;
        curBox = default(Box);

    public bool MoveNext()
        //Avoids going beyond the end of the collection.
        if (++curIndex >= _collection.Count)
            return false;
            // Set current box to next item in collection.
            curBox = _collection[curIndex];
        return true;

    public void Reset() { curIndex = -1; }

    void IDisposable.Dispose() { }

    public Box Current
        get { return curBox; }

    object IEnumerator.Current
        get { return Current; }
' Defines the enumerator for the Boxes collection.
' (Some prefer this class nested in the collection class.)
Public Class BoxEnumerator
    Implements IEnumerator(Of Box)
    Private _collection As BoxCollection
    Private curIndex As Integer
    Private curBox As Box

    Public Sub New(ByVal collection As BoxCollection)
        _collection = collection
        curIndex = -1
        curBox = Nothing

    End Sub

    Private Property Box As Box
    Public Function MoveNext() As Boolean _
        Implements IEnumerator(Of Box).MoveNext
        curIndex = curIndex + 1
        If curIndex = _collection.Count Then
            ' Avoids going beyond the end of the collection.
            Return False
            'Set current box to next item in collection.
            curBox = _collection(curIndex)
        End If
        Return True
    End Function

    Public Sub Reset() _
        Implements IEnumerator(Of Box).Reset
        curIndex = -1
    End Sub

    Public Sub Dispose() _
        Implements IEnumerator(Of Box).Dispose

    End Sub

    Public ReadOnly Property Current() As Box _
        Implements IEnumerator(Of Box).Current

            If curBox Is Nothing Then
                Throw New InvalidOperationException()
            End If

            Return curBox
        End Get
    End Property

    Private ReadOnly Property Current1() As Object _
        Implements IEnumerator.Current

            Return Me.Current
        End Get
    End Property
End Class

' Defines two boxes as equal if they have the same dimensions.
Public Class BoxSameDimensions
    Inherits EqualityComparer(Of Box)

    Public Overrides Function Equals(ByVal b1 As Box, ByVal b2 As Box) As Boolean
        If b1.Height = b2.Height And b1.Length = b2.Length And b1.Width = b2.Width Then
            Return True
            Return False
        End If
    End Function

    Public Overrides Function GetHashCode(ByVal bx As Box) As Integer
        Dim hCode As Integer = bx.Height ^ bx.Length ^ bx.Width
        Return hCode.GetHashCode()
    End Function
End Class


IEnumerator<T> 是所有泛型枚举器的基接口。IEnumerator<T> is the base interface for all generic enumerators.

C#语言的 foreach 语句(for each 中C++For Each Visual Basic)隐藏了枚举器的复杂性。The foreach statement of the C# language (for each in C++, For Each in Visual Basic) hides the complexity of the enumerators. 因此,建议使用 foreach,而不是直接操作枚举数。Therefore, using foreach is recommended, instead of directly manipulating the enumerator.

枚举器可用于读取集合中的数据,但不能用于修改基础集合。Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.

最初,枚举数定位在集合中第一个元素的前面。Initially, the enumerator is positioned before the first element in the collection. 在此位置上,未定义 CurrentAt this position, Current is undefined. 因此,在读取 MoveNext 的值之前,必须调用 Current 将枚举器向前移动到集合的第一个元素。Therefore, you must call MoveNext to advance the enumerator to the first element of the collection before reading the value of Current.

在调用 Current 之前,MoveNext 返回相同的对象。Current returns the same object until MoveNext is called. MoveNextCurrent 设置为下一个元素。MoveNext sets Current to the next element.

如果 MoveNext 越过集合的末尾,则枚举器将定位到集合中的最后一个元素之后,MoveNext 返回 falseIf MoveNext passes the end of the collection, the enumerator is positioned after the last element in the collection and MoveNext returns false. 当枚举器位于此位置时,对 MoveNext 的后续调用也将返回 falseWhen the enumerator is at this position, subsequent calls to MoveNext also return false. 如果对的最后一个调用 MoveNext 返回 false,则 Current 未定义。If the last call to MoveNext returned false, Current is undefined. 无法再次将 Current 设置为集合的第一个元素;必须改为创建新的枚举器实例。You cannot set Current to the first element of the collection again; you must create a new enumerator instance instead.

提供 Reset 方法用于 COM 互操作性。The Reset method is provided for COM interoperability. 它不一定需要实现;相反,实施者可以简单地引发 NotSupportedExceptionIt does not necessarily need to be implemented; instead, the implementer can simply throw a NotSupportedException. 但是,如果你选择执行此操作,则应确保没有调用方依赖于 Reset 功能。However, if you choose to do this, you should make sure no callers are relying on the Reset functionality.

如果对集合所做的更改(如添加、修改或删除元素),则枚举器的行为是不确定的。If changes are made to the collection, such as adding, modifying, or deleting elements, the behavior of the enumerator is undefined.

枚举数没有对集合的独占访问权;因此,从头到尾对一个集合进行枚举在本质上不是一个线程安全的过程。The enumerator does not have exclusive access to the collection; therefore, enumerating through a collection is intrinsically not a thread-safe procedure. 若要确保枚举过程中的线程安全性,可以在整个枚举过程中锁定集合。To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. 若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

System.Collections.Generic 命名空间中集合的默认实现是不同步的。Default implementations of collections in the System.Collections.Generic namespace are not synchronized.


实现此接口需要实现非泛型 IEnumerator 接口。Implementing this interface requires implementing the nongeneric IEnumerator interface. MoveNext()Reset() 方法不依赖于 T,并且仅出现在非泛型接口上。The MoveNext() and Reset() methods do not depend on T, and appear only on the nongeneric interface. Current 属性显示在两个接口上,并且具有不同的返回类型。The Current property appears on both interfaces, and has different return types. 实现非泛型 Current 属性作为显式接口实现。Implement the nongeneric Current property as an explicit interface implementation. 这允许非泛型接口的任何使用者使用泛型接口。This allows any consumer of the nongeneric interface to consume the generic interface.

此外,IEnumerator<T> 实现 IDisposable,这要求您实现 Dispose() 方法。In addition, IEnumerator<T> implements IDisposable, which requires you to implement the Dispose() method. 这使您可以在使用其他资源时关闭数据库连接或释放文件句柄或类似的操作。This enables you to close database connections or release file handles or similar operations when using other resources. 如果没有要释放的其他资源,请提供空的 Dispose() 实现。If there are no additional resources to dispose of, provide an empty Dispose() implementation.



获取集合中位于枚举数当前位置的元素。Gets the element in the collection at the current position of the enumerator.



执行与释放或重置非托管资源关联的应用程序定义的任务。Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

(继承自 IDisposable)

将枚举数推进到集合的下一个元素。Advances the enumerator to the next element of the collection.

(继承自 IEnumerator)

将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。Sets the enumerator to its initial position, which is before the first element in the collection.

(继承自 IEnumerator)