IEnumerator.Reset 方法

定義

設定列舉值至它的初始位置,這是在集合中第一個項目之前。

public:
 void Reset();
public void Reset ();
abstract member Reset : unit -> unit
Public Sub Reset ()

例外狀況

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

範例

下列程式碼範例示範自訂集合介面 IEnumerator 的實作。 在此範例中, Reset 不會明確呼叫 ,但實作以支援在 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 是未定義的。

方法 Reset 提供 COM 互通性。 它不一定需要實作;相反地,實作者可以直接擲回 NotSupportedException

給實施者的注意事項

對 的所有呼叫 Reset() 都必須產生列舉值相同的狀態。 慣用的實作是在第一個專案之前,將列舉值移至集合的開頭。 如果自建立列舉值之後已修改集合,這會使列舉值失效,這與 MoveNext()Current 一致。

適用於

另請參閱