在已實現非泛型 IDictionary、IEnumerable 基礎上,實現泛型 IDictionary<TKey,TValue> 介面,提供類型安全的鍵值操作、索引器、Keys/Values 強類型集合視圖。
public class ReversibleSortedList :
IDictionary,
IDictionary,
ICollection>,
IEnumerable>,
ICollection,
IEnumerable
{
// ... 現有欄位與方法
}
bool ICollection>.IsReadOnly => false;
void ICollection>.Add(KeyValuePair item)
=> Add(item.Key, item.Value);
bool ICollection>.Contains(KeyValuePair item)
{
int idx = IndexOfKey(item.Key);
return idx >= 0 && EqualityComparer.Default.Equals(_values[idx], item.Value);
}
void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex)
{
if (array == null) throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length) throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length - arrayIndex < Count) throw new ArgumentException("目標陣列空間不足");
for (int i = 0; i < Count; i++)
array[arrayIndex + i] = new KeyValuePair(_keys[i], _values[i]);
}
bool ICollection>.Remove(KeyValuePair item)
{
int idx = IndexOfKey(item.Key);
if (idx >= 0 && EqualityComparer.Default.Equals(_values[idx], item.Value))
{
RemoveAt(idx);
return true;
}
return false;
}
// 強類型 Keys/Values 集合視圖
public IList Keys => GetKeyListHelper();
public IList Values => GetValueListHelper();
// 索引器:Get 或 Add/Update
public TValue this[TKey key]
{
get
{
int idx = IndexOfKey(key);
return idx >= 0 ? _values[idx] : default(TValue);
}
set
{
if (key == null) throw new ArgumentNullException(nameof(key));
int idx = Array.BinarySearch(_keys, 0, _size, key, _comparer);
if (idx >= 0)
{
_values[idx] = value;
_version++;
}
else
{
Insert(~idx, key, value); // ~idx = 插入位置
}
}
}
public bool Remove(TKey key)
{
int idx = IndexOfKey(key);
if (idx >= 0) { RemoveAt(idx); return true; }
return false;
}
public bool TryGetValue(TKey key, out TValue value)
{
int idx = IndexOfKey(key);
if (idx >= 0) { value = _values[idx]; return true; }
value = default(TValue);
return false;
}
public void RemoveAt(int index)
{
if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index));
_size--;
if (index < _size)
{
Array.Copy(_keys, index + 1, _keys, index, _size - index);
Array.Copy(_values, index + 1, _values, index, _size - index);
}
_keys[_size] = default(TKey);
_values[_size] = default(TValue);
_version++;
}
// 內部插入(索引已驗證)
private void Insert(int index, TKey key, TValue value)
{
if (_size == _keys.Length) EnsureCapacity(_size + 1);
if (index < _size)
{
Array.Copy(_keys, index, _keys, index + 1, _size - index);
Array.Copy(_values, index, _values, index + 1, _size - index);
}
_keys[index] = key;
_values[index] = value;
_size++; _version++;
}
static void Main()
{
var rs = new ReversibleSortedList();
rs.Add("3", "a"); rs.Add("1", "b"); rs.Add("2", "c");
rs.Add("6", "d"); rs.Add("5", "e"); rs.Add("4", "f");
Console.WriteLine("遍歷 (KeyValuePair):");
foreach (var kv in rs) Console.WriteLine($"{kv.Key} {kv.Value}");
Console.WriteLine("\n刪除鍵 \"2\" 和 \"5\":");
rs.Remove("2"); rs.Remove("5");
foreach (var kv in rs) Console.WriteLine($"{kv.Key} {kv.Value}");
Console.WriteLine("\n索引器測試:");
Console.WriteLine($"rs[\"3\"] = {rs["3"]}"); // a
rs["3"] = "updated";
Console.WriteLine($"rs[\"3\"] = {rs["3"]}"); // updated
rs["9"] = "new"; // 新增
Console.WriteLine($"rs[\"9\"] = {rs["9"]}"); // new
Console.WriteLine($"\nTryGetValue(\"1\"): {rs.TryGetValue("1", out var v)}, v={v}");
Console.WriteLine($"ContainsKey(\"6\"): {rs.ContainsKey("6")}");
}
輸出驗證所有操作符合預期,泛型介面實現完成。