封裝外部集合參考,轉呼外部輔助方法:
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();
}
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 陣列。此設計達到「唯讀檢視、零複製、版本安全」三大目標。