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

打造可逆向排序的泛型字典類 (五 續):列舉器完整程式碼與 Current 屬性多型實作

     編輯:關於C語言

Enumerator 結構體完整原始碼

private struct Enumerator<K, V> : 
    IEnumerator<KeyValuePair<K, V>>, IDisposable,
    IDictionaryEnumerator, IEnumerator
{
    private ReversibleSortedList<K, V> _list;
    private K _key; private V _value;
    private int _index, _version;

    internal Enumerator(ReversibleSortedList<K, V> list)
    {
        _list = list; _index = 0; _version = list.version;
        _key = default(K); _value = default(V);
    }

    public void Dispose() { _index = 0; _key = default(K); _value = default(V); }

    // IDictionaryEnumerator.Key
    object IDictionaryEnumerator.Key
    {
        get
        {
            if (_index == 0 || _index == _list.Count + 1)
                throw new InvalidOperationException("無法列舉。");
            return _key;
        }
    }

    public bool MoveNext() { /* 見上節 */ }

    // IDictionaryEnumerator.Entry
    DictionaryEntry IDictionaryEnumerator.Entry
    {
        get
        {
            if (_index == 0 || _index == _list.Count + 1)
                throw new InvalidOperationException("無法列舉。");
            return new DictionaryEntry(_key, _value);
        }
    }

    // IEnumerator.Current
    public KeyValuePair<K, V> Current => new KeyValuePair<K, V>(_key, _value);

    // IEnumerator.Current (非泛型)
    object IEnumerator.Current
    {
        get
        {
            if (_index == 0 || _index == _list.Count + 1)
                throw new InvalidOperationException("無法列舉。");
            return new DictionaryEntry(_key, _value);
        }
    }

    // IDictionaryEnumerator.Value
    object IDictionaryEnumerator.Value
    {
        get
        {
            if (_index == 0 || _index == _list.Count + 1)
                throw new InvalidOperationException("無法列舉。");
            return _value;
        }
    }

    void IEnumerator.Reset()
    {
        if (_version != _list.version)
            throw new InvalidOperationException("列舉版本檢查失敗!");
        _index = 0; _key = default(K); _value = default(V);
    }
}

此設計直接引用外部陣列元素,避免複製帶來的效能損耗;版本機制確保集合異動時列舉器即時拋出例外。

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