IEnumerator.Current 属性

定义

获取集合中位于枚举数当前位置的元素。

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

属性值

Object

集合中位于枚举数当前位置的元素。

示例

下面的代码示例演示自定义集合的接口的实现 IEnumerator 。 在此示例中,Current未显式调用,但它实现以支持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

注解

Current 在以下任一条件下未定义:

  • 枚举器位于集合中的第一个元素之前,紧接着创建枚举器。 MoveNext 必须在读取值 Current之前调用枚举器将枚举器提升到集合的第一个元素。

  • 返回MoveNextfalse的最后一次调用,指示集合的结尾。

  • 由于集合中所做的更改(例如添加、修改或删除元素),枚举器失效。

在调用 Current 之前,MoveNext 返回相同的对象。 MoveNextCurrent 设置为下一个元素。

适用于

另请参阅