英語で読む

次の方法で共有


IEnumerator.MoveNext メソッド

定義

列挙子をコレクションの次の要素に進めます。

C#
public bool MoveNext ();

戻り値

列挙子が次の要素に正常に進んだ場合は true。列挙子がコレクションの末尾を越えた場合は false

例外

コレクションは、列挙子の作成後に変更されました。

次のコード例は、カスタム コレクションのインターフェイスの IEnumerator 実装を示しています。 この例では、 MoveNext は明示的に呼び出されませんが、 (Visual Basic では)for eachforeach使用をサポートするために実装されています。 このコード例は、 インターフェイスの大きな例の 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 がコレクションの末尾を通過した場合、列挙子がコレクション内の最後の要素の後に配置され、MoveNextfalse を返します。 列挙子がこの位置にある場合、後続の をMoveNext呼び出すと、 が呼び出されるまでResetも が返falseされます。

要素の追加、変更、削除など、コレクションに変更が加えられた場合、 の 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

こちらもご覧ください