統一規範降低學習成本,並讓自訂集合能與 foreach、資料繫結等框架機制無縫整合。IDictionary 繼承 ICollection、IEnumerable,代表鍵值對非泛型集合。
以下 SimpleDictionary 示範核心成員:陣列儲存、DictionaryEntry 封裝鍵值、索引器、列舉器、Keys/Values 集合回傳:
public class SimpleDictionary : IDictionary
{
private DictionaryEntry[] items;
private int ItemsInUse = 0;
public SimpleDictionary(int numItems) { items = new DictionaryEntry[numItems]; }
public bool Contains(object key) => TryGetIndexOfKey(key, out _);
public void Remove(object key) { /* 位移陣列元素 */ }
public void Clear() { ItemsInUse = 0; }
public void Add(object key, object value) { items[ItemsInUse++] = new DictionaryEntry(key, value); }
public ICollection Keys { get { /* 複製鍵到新陣列 */ } }
public ICollection Values { get { /* 複製值到新陣列 */ } }
public object this[object key]
{
get { /* 查找回傳值或 null */ }
set { /* 存在則更新,否則 Add */ }
}
// 內部列舉器實作 IDictionaryEnumerator
private class SimpleDictionaryEnumerator : IDictionaryEnumerator { /* ... */ }
public IDictionaryEnumerator GetEnumerator() => new SimpleDictionaryEnumerator(this);
// ICollection, IEnumerable 成員略
}
字典元素個數= 3
字典中是否包含'Jeff'? True
Jeff的年齡是:40
Jeff is 40 years old.
Kristin is 34 years old.
Aidan is 1 years old.
Jeff
Kristin
Aidan
40
34
1
此範例為後續在 ReversibleSortedList 實作完整 IDictionary 奠基。