Share via


IEnumerator.MoveNext 方法

将枚举数推进到集合的下一个元素。

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

语法

声明
Function MoveNext As Boolean
用法
Dim instance As IEnumerator
Dim returnValue As Boolean

returnValue = instance.MoveNext
bool MoveNext ()
bool MoveNext ()
boolean MoveNext ()
function MoveNext () : boolean

返回值

如果枚举数成功地推进到下一个元素,则为 true;如果枚举数越过集合的结尾,则为 false

异常

异常类型 条件

InvalidOperationException

在创建了枚举数后集合被修改了。

备注

在创建枚举数之后或在调用 Reset 方法后,枚举数放置在集合的第一个元素之前,首次调用 MoveNext 方法会将枚举数移到集合的第一个元素。

如果 MoveNext 越过集合的末尾,则枚举数将被放置在此集合中最后一个元素的后面,而且 MoveNext 返回 false。当枚举数位于此位置时,在调用 Reset 之前,对 MoveNext 的后续调用也返回 false

只要集合保持不变,枚举数就保持有效。如果对集合进行了更改(如添加、修改或删除元素),则枚举数将失效且不可恢复,并且下一次对 MoveNextReset 的调用将引发 InvalidOperationException

示例

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

Public Class PeopleEnum
    Implements IEnumerator

    Public _people() As Person

    ' Enumerators are positioned before the first element
    ' until the first MoveNext() call.
    Dim position As Integer = -1

    Public Sub New(ByVal list() As Person)
        _people = list
    End Sub

    Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
        position = position + 1
        Return (position < _people.Length)
    End Function

    Public Sub Reset() Implements IEnumerator.Reset
        position = -1
    End Sub

    Public ReadOnly Property Current() As Object Implements IEnumerator.Current
        Get
            Try
                Return _people(position)
            Catch ex As IndexOutOfRangeException
                Throw New InvalidOperationException()
            End Try
        End Get
    End Property
End Class
public class PeopleEnum : IEnumerator
{
    public Person[] _people;

    // Enumerators are positioned before the first element
    // until the first MoveNext() call.
    int position = -1;

    public PeopleEnum(Person[] list)
    {
        _people = list;
    }

    public bool MoveNext()
    {
        position++;
        return (position < _people.Length);
    }

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

    public object Current
    {
        get
        {
            try
            {
                return _people[position];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }
}

平台

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

请参见

参考

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