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

打造可逆向排序的泛型字典類 (六 續):KeyList/ValueList 內部類別完整實作

     編輯:關於C語言

KeyList 實作 IList<TKey>

封裝外部集合參考,轉呼外部輔助方法:

private class KeyList<TKey, TValue> : IList<TKey>, ICollection<TKey>, IEnumerable<TKey>, IEnumerable
{
    private ReversibleSortedList<TKey, TValue> _dict;
    internal KeyList(ReversibleSortedList<TKey, TValue> dict) { _dict = dict; }

    public TKey this[int index] { get => _dict.GetKey(index); set => throw new NotSupportedException(); }
    public int Count => _dict.Count;
    public bool IsReadOnly => true;
    public int IndexOf(TKey item) => _dict.IndexOfKey(item);
    public void Insert(int index, TKey item) => throw new NotSupportedException();
    public void RemoveAt(int index) => throw new NotSupportedException();
    public void Add(TKey item) => throw new NotSupportedException();
    public void Clear() => throw new NotSupportedException();
    public bool Contains(TKey item) => _dict.ContainsKey(item);
    public void CopyTo(TKey[] array, int arrayIndex) { /* 複製 keys 陣列區段 */ }
    public IEnumerator<TKey> GetEnumerator() => new KeyEnumerator(_dict);
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

KeyEnumerator 結構體

private struct KeyEnumerator : IEnumerator<TKey>, IDisposable, IEnumerator
{
    private ReversibleSortedList<TKey, TValue> _dict;
    private TKey _current; private int _index, _version;
    internal KeyEnumerator(ReversibleSortedList<TKey, TValue> dict) { _dict = dict; _version = dict.version; }
    public bool MoveNext() { /* 版本檢查、推進索引、取 keys[_index] */ }
    public TKey Current => _current;
    object IEnumerator.Current => _current;
    void IEnumerator.Reset() { /* 版本檢查、重置索引 */ }
    public void Dispose() { _index = 0; _current = default; }
}

ValueList 與 ValueEnumerator 結構同理,僅操作 values 陣列。此設計達到「唯讀檢視、零複製、版本安全」三大目標。

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