IEnumerator.MoveNext 方法
本文內容
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將列舉值往前推至下集合中的下一個項目。
public:
bool MoveNext();
public bool MoveNext ();
abstract member MoveNext : unit -> bool
Public Function MoveNext () As Boolean
如果列舉值成功前移至下一個項目,則為 true;如果列舉值超過集合的結尾,則為 false。
建立列舉值之後,集合已修改。
下列程式代碼範例示範自定義集合介面的 IEnumerator 實作。 在此範例中, MoveNext 不會明確呼叫 ,但會實作以支援在Visual Basic) 中使用 foreach (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 為未定義。
| 產品 | 版本 |
|---|---|
| .NET | Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9 |
| .NET Framework | 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1 |
| .NET Standard | 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1 |
| UWP | 10.0 |