首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

打造可逆向排序的泛型字典類 (六 再續):ValueEnumerator 結構體完整代碼

     編輯:關於C語言

ValueEnumerator 實作細節


private sealed class ReversibleSortedListValueEnumerator : 
    IEnumerator<TValue>, IDisposable, IEnumerator
{
    private ReversibleSortedList<TKey, TValue> _dict;
    private TValue _currentValue;
    private int _index, _version;

    internal ReversibleSortedListValueEnumerator(ReversibleSortedList<TKey, TValue> dict)
    { _dict = dict; _version = dict.version; }

    public void Dispose() { _index = 0; _currentValue = default; }

    public bool MoveNext()
    {
        if (_version != _dict.version) throw new InvalidOperationException("Enumeration failed version check");
        if (_index < _dict.Count)
        { _currentValue = _dict.values[_index]; _index++; return true; }
        _index = _dict.Count + 1; _currentValue = default; return false;
    }

    void IEnumerator.Reset()
    {
        if (_version != _dict.version) throw new InvalidOperationException("Enumeration failed version check");
        _index = 0; _currentValue = default;
    }

    public TValue Current => _currentValue;
    object IEnumerator.Current
    {
        get
        {
            if (_index == 0 || _index == _dict.Count + 1) throw new InvalidOperationException("Enumeration Operation could not occur");
            return _currentValue;
        }
    }
}

與 KeyEnumerator 鏡像對稱,唯讀取 values 陣列。所有列舉器共用版本檢查模式,確保集合異動時即時失效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved