IEnumerator.Reset 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将枚举器设置为其初始位置,该位置位于集合中的第一个元素之前。
public:
void Reset();
public void Reset();
abstract member Reset : unit -> unit
Public Sub Reset ()
例外
创建枚举器后修改了集合。
枚举器不支持重置。
示例
下面的代码示例演示自定义集合接口的 IEnumerator 实现。 在此示例中, Reset 未显式调用,但它实现为支持在 Visual Basic 中使用 foreach (for 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() 枚举器的所有调用都必须产生相同的状态。 首选实现是在第一个元素之前将枚举器移到集合的开头。 如果自创建枚举器后已修改集合(与枚举器一致且Current一MoveNext()致),则这会使枚举器失效。