IEnumerator.MoveNext 方法

定义

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

C#
public bool MoveNext ();

返回

如果枚举数已成功地推进到下一个元素,则为 true;如果枚举数传递到集合的末尾,则为 false

例外

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

示例

下面的代码示例演示自定义集合接口 IEnumerator 的实现。 在此示例中, MoveNext 未显式调用 ,但实现它以支持在 Visual Basic) 中使用 foreach (for each 。 此代码示例是 接口的较大示例的 IEnumerator 一部分。

C#
// When you implement IEnumerable, you must also implement IEnumerator.
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;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

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

注解

创建枚举器后或调用 方法后 Reset ,枚举器位于集合的第一个元素之前,对 方法的第一次调用 MoveNext 会将枚举器移到集合的第一个元素上。

如果 MoveNext 传递集合的末尾,则枚举器位于集合中的最后一个元素之后,并 MoveNext 返回 false。 当枚举器位于此位置时,对 的后续调用 MoveNext 也会返回 false ,直到 Reset 调用。

如果对集合进行了更改(例如添加、修改或删除元素),则 的行为 MoveNext 未定义。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另请参阅