共用方式為


IEnumerator.MoveNext 方法

定義

將列舉值往前推至下集合中的下一個項目。

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

傳回

如果列舉值成功前移至下一個項目,則為 true;如果列舉值超過集合的結尾,則為 false

例外狀況

建立列舉值之後,集合已修改。

範例

下列程式代碼範例示範自定義集合介面的 IEnumerator 實作。 在此範例中, MoveNext 不會明確呼叫 ,但會實作以支援在Visual Basic) 中使用 foreach (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 傳遞集合結尾,列舉值會放在集合的最後一個專案後面,並 MoveNextfalse回 。 當列舉值位於這個位置時,後續呼叫 MoveNext 也會傳回 false ,直到呼叫 為止 Reset

如果對集合進行變更,例如新增、修改或刪除專案,則 的行為 MoveNext 為未定義。

適用於

另請參閱