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

打造可逆向排序的泛型字典類 (四):IDictionary 介面實作範例 (簡易版)

     編輯:關於C語言

為何實作標準介面

統一規範降低學習成本,並讓自訂集合能與 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 奠基。

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