IEnumerable.GetEnumerator 方法

返回一个循环访问集合的枚举数。

**命名空间:**System.Collections
**程序集:**mscorlib(在 mscorlib.dll 中)

语法

声明
Function GetEnumerator As IEnumerator
用法
Dim instance As IEnumerable
Dim returnValue As IEnumerator

returnValue = instance.GetEnumerator
IEnumerator GetEnumerator ()
IEnumerator^ GetEnumerator ()
IEnumerator GetEnumerator ()
function GetEnumerator () : IEnumerator

返回值

可用于循环访问集合的 IEnumerator 对象。

备注

C# 语言的 foreach 语句(在 Visual Basic 中为 for each)隐藏了枚举数的复杂性。因此,建议使用 foreach,而不直接操作枚举数。

枚举数可用于读取集合中的数据,但不能用于修改基础集合。

最初,枚举数定位在集合中第一个元素前。Reset 方法还会将枚举数返回到此位置。在此位置上,Current 属性未定义。因此,在读取 Current 的值之前,必须调用 MoveNext 方法将枚举数提前到集合的第一个元素。

在调用 MoveNextReset 之前,Current 返回同一对象。MoveNextCurrent 设置为下一个元素。

如果 MoveNext 越过集合的末尾,则枚举数将被放置在此集合中最后一个元素的后面,而且 MoveNext 返回 false。当枚举数位于此位置时,对 MoveNext 的后续调用也返回 false。如果上一个 MoveNext 调用返回 false,则 Current 未定义。若要再次将 Current 设置为集合的第一个元素,可以调用 Reset,然后再调用 MoveNext

只要集合保持不变,枚举数就保持有效。如果对集合进行更改(如添加、修改或删除元素),则枚举数将失效且不可恢复,而且其行为是不确定的。

枚举数没有对集合的独占访问权;因此,枚举通过集合在本质上不是一个线程安全的过程。若要确保枚举过程中的线程安全,可以在整个枚举过程中锁定集合。若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。

示例

下面的代码示例演示如何实现自定义集合的 IEnumerable 接口。在此示例中,没有显式调用但实现了 GetEnumerator,以便支持使用 foreach(在 Visual Basic 中为 for each)。此代码示例摘自 IEnumerable 接口的一个更大的示例。

Public Class People
    Implements IEnumerable

    Private _people() As Person

    Public Sub New(ByVal pArray() As Person)
        _people = New Person(pArray.Length - 1) {}

        Dim i As Integer
        For i = 0 To pArray.Length - 1
            _people(i) = pArray(i)
        Next i
    End Sub

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

        Return New PeopleEnum(_people)
    End Function

End Class
public class People : IEnumerable
{
    private Person[] _people;
    public People(Person[] pArray)
    {
        _people = new Person[pArray.Length];

        for (int i = 0; i < pArray.Length; i++)
        {
            _people[i] = pArray[i];
        }
    }

    public IEnumerator GetEnumerator()
    {
        return new PeopleEnum(_people);
    }
}

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

IEnumerable 接口
IEnumerable 成员
System.Collections 命名空间
IEnumerator