IEnumerator.MoveNext 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將列舉器前進至集合的下一個元素。
public:
bool MoveNext();
public bool MoveNext();
abstract member MoveNext : unit -> bool
Public Function MoveNext () As Boolean
傳回
true 若枚舉器成功推進至下一個元素; false 如果列舉員已完成該集合。
例外狀況
在普查員成立後,該收藏進行了修改。
範例
以下程式碼範例展示了自訂集合介面的實作 IEnumerator 。 在此範例中,MoveNext未明確呼叫,但實作以支援 (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 ,列舉器會被放置在集合的第一個元素之前,而第一次呼叫該 MoveNext 方法時,列舉器會移動到集合的第一個元素。
若 MoveNext 通過集合的末尾,列舉器會位於集合的最後一個元素之後,並 MoveNext 返回 false。 當列舉器處於此位置時,後續的回傳MoveNextfalse呼叫也會持續到Reset被呼叫為止。
若對集合進行變更,例如新增、修改或刪除元素,則 的 MoveNext 行為未定義。