IEnumerator.Reset 方法
将枚举数设置为其初始位置,该位置位于集合中第一个元素之前。
**命名空间:**System.Collections
**程序集:**mscorlib(在 mscorlib.dll 中)
语法
声明
Sub Reset
用法
Dim instance As IEnumerator
instance.Reset
void Reset ()
void Reset ()
void Reset ()
function Reset ()
异常
异常类型 | 条件 |
---|---|
在创建了枚举数后集合被修改了。 |
备注
只要集合保持不变,枚举数就保持有效。如果对集合进行了更改(如添加、修改或删除元素),则该枚举数将失效且不可恢复,并且下一次调用 MoveNext 或 Reset 方法会引发 InvalidOperationException。
给实现者的说明 对 Reset 的所有调用必须导致枚举数的同一状态。首选实现是将枚举数移动到集合的开始处(第一个元素之前)。如果在创建枚举数后对集合进行了修改,首选实现将使枚举数失效,这与 MoveNext 和 Current 一致。
示例
下面的代码示例演示如何实现自定义集合的 IEnumerator 接口。在此示例中,没有显式调用但实现了 Reset,以便支持使用 foreach(在 Visual Basic 中为 for each)。此代码示例摘自 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
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;
}
public object Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
平台
Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition
.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求。
版本信息
.NET Framework
受以下版本支持:2.0、1.1、1.0
.NET Compact Framework
受以下版本支持:2.0、1.0
请参见
参考
IEnumerator 接口
IEnumerator 成员
System.Collections 命名空间
MoveNext
Current