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

ReversibleSortedList<TKey, TValue> 建構子完整實現:七種多載覆蓋所有初始化場景

     編輯:關於C語言

前言

ReversibleSortedList<TKey, TValue> 提供七個建構子多載,涵蓋無參、指定比較器、指定字典、指定容量、指定字典與比較器、指定容量與比較器等所有常見初始化需求。本文逐一解析各建構子的實現邏輯與設計意圖。

靜態建構子:共享空陣列單例

static ReversibleSortedList()
{
    emptyKeys = new TKey[0];
    emptyValues = new TValue[0];
}

採用單例模式提供共享空陣列,避免每個空實例重複配置陣列物件,節省記憶體與 GC 壓力。

七個建構子詳解

1. 無參建構子 - 最輕量初始化

public ReversibleSortedList()
{
    keys = emptyKeys;
    values = emptyValues;
    _size = 0;
    _sortDirectionComparer = new SortDirectionComparer<TKey>();
    _currentSortDirection = _sortDirectionComparer.SortDirection;
}

直接引用靜態空陣列,建立預設升序比較器,零配置開銷。

2. 指定比較器建構子 - 自訂排序邏輯

public ReversibleSortedList(SortDirectionComparer<TKey> comparer) : this()
{
    if (comparer != null)
    {
        _sortDirectionComparer = comparer;
        _currentSortDirection = _sortDirectionComparer.SortDirection;
    }
}

鏈呼叫無參建構子,再替換比較器。支援外部傳入 IComparer<TKey> 實現完全自訂排序(如忽略大小寫、文化特定排序)。

3. 指定字典建構子 - 從現有字典複製

public ReversibleSortedList(IDictionary<TKey, TValue> dictionary)
    : this(dictionary, (SortDirectionComparer<TKey>)null) { }

委派給下一個多載,傳入 null 比較器使用預設排序。

4. 指定容量建構子 - 預分配避免擴容

public ReversibleSortedList(int capacity)
{
    if (capacity < 0) throw new ArgumentOutOfRangeException(...);
    keys = new TKey[capacity];
    values = new TValue[capacity];
    _sortDirectionComparer = new SortDirectionComparer<TKey>();
    _currentSortDirection = _sortDirectionComparer.SortDirection;
}

直接配置指定大小陣列,適合預知大概元素數量的場景,消除擴容開銷。

5. 字典+比較器建構子 - 完整複製並排序

public ReversibleSortedList(IDictionary<TKey, TValue> dictionary,
    SortDirectionComparer<TKey> comparer)
    : this((dictionary != null) ? dictionary.Count : 0, comparer)
{
    if (dictionary == null) throw new ArgumentNullException("dictionary");
    dictionary.Keys.CopyTo(keys, 0);
    dictionary.Values.CopyTo(values, 0);
    Array.Sort(keys, values, _sortDirectionComparer);
    _size = dictionary.Count;
}

關鍵步驟:

  1. 委派容量建構子預分配陣列
  2. CopyTo 批次複製鍵值陣列
  3. Array.Sort(keys, values, comparer) 同步排序兩平行陣列

時間複雜度 O(n log n),一次性完成初始化與排序。

6. 容量+比較器建構子 - 預分配+自訂排序

public ReversibleSortedList(int capacity, SortDirectionComparer<TKey> comparer)
    : this(comparer)
{
    Capacity = capacity; // 觸發容量設定邏輯
}

先建立比較器,再設定容量屬性(內部會配置新陣列並複製現有資料,此處為空陣列故無複製成本)。

7. 私有輔助建構子 - 內部克隆用

原始碼中未直接展示,但 Capacity 屬性設定器、TrimExcess 等方法會內部建立新陣列並複製資料,實現類似複製建構子的功能。

設計模式總結

  • 建構子鏈:層層委派,避免重複初始化邏輯
  • 參數驗證前置:null 檢查、容量非負檢查
  • 延遲配置:空實例共享靜態空陣列
  • 批次操作:CopyTo + Array.Sort 替代逐筆 Add

總結

七個建構子形成完整的初始化矩陣,滿足從「極輕量空實例」到「大量資料預排序匯入」的全譜系需求。原始碼展現了框架級集合的工程化思維:效能優先、API 正交、資源節制。研讀此類建構子設計,對掌握高品質類別庫開發極具參考價值。

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