IEnumerator.Current 屬性

定義

取得集合中位於列舉值目前位置的元素。

public object Current { get; }
public object? Current { get; }

屬性值

位於列舉值中目前位置的集合中的元素。

範例

下列程式代碼範例示範自定義集合介面的 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();
            }
        }
    }
}

備註

Current 在下列任一情況下未定義:

  • 列舉值位於集合中的第一個專案之前,緊接在建立列舉值之後。 MoveNext 必須先呼叫 ,才能將列舉值前移至集合的第一個專案,才能讀取的值 Current

  • 最後一 MoveNext 次呼叫傳 false回的 ,表示集合的結尾。

  • 列舉值因為集合中所做的變更而失效,例如新增、修改或刪除專案。

Current 會傳回相同的物件直到呼叫 MoveNextMoveNext 會將 Current 設定為下一個項目。

適用於

產品 版本
.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

另請參閱