Language

IEnumerator.MoveNext メソッド

定義

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

public:
 bool MoveNext();
public bool MoveNext();
abstract member MoveNext : unit -> bool
Public Function MoveNext () As Boolean

返品

true 列挙子が次の要素に正常に進んだ場合。列挙子がコレクションの末尾を通過した場合に false します。

例外

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

例

次のコード例は、カスタム コレクションの IEnumerator インターフェイスの実装を示しています。 この例では、 MoveNext は明示的に呼び出されませんが、 foreach の使用をサポートするように実装されています (Visual Basic のfor each )。 このコード例は、 IEnumerator インターフェイスの大きな例の一部です。

// 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();
            }
        }
    }
}
' When you implement IEnumerable, you must also implement 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

注釈

列挙子が作成された後、または Reset メソッドが呼び出された後、列挙子はコレクションの最初の要素の前に配置され、 MoveNext メソッドの最初の呼び出しは、列挙子をコレクションの最初の要素に移動します。

MoveNextコレクションの末尾を渡すと、列挙子はコレクション内の最後の要素の後に配置され、MoveNextはfalseを返します。 列挙子がこの位置にある場合、後続のMoveNextの呼び出しでは、falseが呼び出されるまでResetも返されます。

要素の追加、変更、削除など、コレクションに変更が加えられた場合、 MoveNext の動作は未定義です。

適用対象

こちらもご覧ください