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

打造可逆向排序的泛型字典類 (六):Keys/Values 屬性回傳 IList<T> 實作與測試

     編輯:關於C語言

引入 KeyList 與 ValueList 內部類別

為支援索引存取並避免陣列複製,Keys/Values 回傳實作 IList<T> 的內部包裝類別:

private KeyList<TKey, TValue> _keyList;
private ValueList<TKey, TValue> _valueList;

public IList<TKey> Keys => GetKeyListHelper();
public IList<TValue> Values => GetValueListHelper();

private KeyList<TKey, TValue> GetKeyListHelper()
    => _keyList ??= new KeyList<TKey, TValue>(this);
private ValueList<TKey, TValue> GetValueListHelper()
    => _valueList ??= new ValueList<TKey, TValue>(this);

外部類別需提供的輔助方法

public int IndexOfKey(TKey key) { /* BinarySearch */ }
public int IndexOfValue(TValue value) => Array.IndexOf(values, value, 0, _size);
public bool ContainsKey(TKey key) => IndexOfKey(key) >= 0;
public bool ContainsValue(TValue value) => IndexOfValue(value) >= 0;

private TValue GetByIndex(int index) { /* 範圍檢查回傳 values[index] */ }
private TKey GetKey(int index) { /* 範圍檢查回傳 keys[index] */ }
private void Insert(int index, TKey key, TValue value) { /* 位移陣列並插入,更新 _size、version */ }

測試輸出

1 b
2 c
3 a
4 f
5 e
6 d
1 2 3 4 5 6
b c a f e d
4
e

驗證 foreach、索引存取 Keys[3]、Values[4] 均正常運作。

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