IEnumerator.Current Свойство
Определение
Возвращает элемент коллекции, соответствующий текущей позиции перечислителя.Gets the element in the collection at the current position of the enumerator.
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
Значение свойства
Элемент коллекции, соответствующий текущей позиции перечислителя.The element in the collection at the current position of the enumerator.
Примеры
В следующем примере кода демонстрируется реализация IEnumerator интерфейсов для пользовательской коллекции.The following code example demonstrates the implementation of the IEnumerator interfaces for a custom collection. В этом примере Current не вызывается явно, но реализуется для поддержки использования foreach
( for each
в Visual Basic).In this example, Current is not explicitly called, but it is implemented to support the use of foreach
(for each
in Visual Basic). Этот пример кода является частью более крупного примера для IEnumerator интерфейса.This code example is part of a larger example for the IEnumerator interface.
// 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 не определено при выполнении любого из следующих условий:Current is undefined under any of the following conditions:
Перечислитель располагается перед первым элементом в коллекции сразу после создания перечислителя.The enumerator is positioned before the first element in the collection, immediately after the enumerator is created. MoveNext необходимо вызвать метод, чтобы переместить перечислитель к первому элементу коллекции перед считыванием значения Current .MoveNext must be called to advance the enumerator to the first element of the collection before reading the value of Current.
Последний вызов MoveNext возвращен
false
, который указывает на конец коллекции.The last call to MoveNext returnedfalse
, which indicates the end of the collection.Перечислитель становится недействительным из-за изменений, внесенных в коллекцию, таких как добавление, изменение или удаление элементов.The enumerator is invalidated due to changes made in the collection, such as adding, modifying, or deleting elements.
Current возвращает тот же объект, пока не будет вызван метод MoveNext.Current returns the same object until MoveNext is called. MoveNext задает Current в качестве значения для следующего элемента.MoveNext sets Current to the next element.