IEnumerator.Reset 方法

定義

將列舉值設定為其初始位置,也就是集合中第一個專案之前。

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

例外狀況

在普查員成立後,該收藏進行了修改。

列舉器不支援重置。

範例

以下程式碼範例展示了自訂集合介面的實作 IEnumerator 。 在此範例中,Reset未明確呼叫,但實作以支援 (foreachfor each在 Visual Basic 中)。 此程式碼範例是介面更大範例 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,則列舉子無效。

適用於

另請參閱