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

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

     編輯:關於C語言

KeyEnumerator 完整實作


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

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

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

    public bool MoveNext()
    {
        if (_version != _dict.version) throw new InvalidOperationException("枚舉版本檢查錯誤");
        if (_index < _dict.Count)
        { _currentKey = _dict.keys[_index]; _index++; return true; }
        _index = _dict.Count + 1; _currentKey = default; return false;
    }

    void IEnumerator.Reset()
    {
        if (_version != _dict.version) throw new InvalidOperationException("枚舉版本檢查錯誤");
        _index = 0; _currentKey = default;
    }

    public TKey Current => _currentKey;
    object IEnumerator.Current
    {
        get
        {
            if (_index == 0 || _index == _dict.Count + 1) throw new InvalidOperationException("不能進行枚舉操作");
            return _currentKey;
        }
    }
}

此列舉器直接讀取外部 keys 陣列,無需考慮排序方向(外部已維持有序)。同樣採用版本號機制偵測並發修改。

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