IEnumerator.MoveNext 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
将枚举数推进到集合的下一个元素。
public:
bool MoveNext();
public bool MoveNext ();
abstract member MoveNext : unit -> bool
Public Function MoveNext () As Boolean
返回
如果枚举数已成功地推进到下一个元素,则为 true
;如果枚举数传递到集合的末尾,则为 false
。
例外
集合在枚举器创建后被修改。
示例
下面的代码示例演示自定义集合的接口的实现 IEnumerator 。 在此示例中,MoveNext未显式调用,但它实现以支持foreach
在Visual Basic) 中使用 (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 传递集合的末尾,则枚举器将定位在集合中的最后一个元素之后并 MoveNext 返回 false
。 当枚举器处于此位置时,后续调用 MoveNext 也会返回 false
,直到 Reset 调用为止。
如果对集合进行了更改,例如添加、修改或删除元素,则未定义其行为 MoveNext 。