為支援索引存取並避免陣列複製,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] 均正常運作。