IEnumerator.Current 屬性
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得集合中位於列舉值目前位置的元素。
public:
property System::Object ^ Current { System::Object ^ get(); };
public object Current { get; }
public object? Current { get; }
member this.Current : obj
Public ReadOnly Property Current As Object
屬性值
位於列舉值中目前位置的集合中的元素。
範例
下列程式代碼範例示範自定義集合介面的 IEnumerator 實作。 在此範例中, Current 不會明確呼叫 ,但會實作以支援在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
備註
Current 在下列任一情況下未定義:
列舉值位於集合中的第一個專案之前,緊接在建立列舉值之後。 MoveNext 必須先呼叫 ,才能將列舉值前移至集合的第一個專案,才能讀取的值 Current。
最後一 MoveNext 次呼叫傳
false
回的 ,表示集合的結尾。列舉值因為集合中所做的變更而失效,例如新增、修改或刪除專案。
Current 會傳回相同的物件直到呼叫 MoveNext。 MoveNext 會將 Current 設定為下一個項目。