ReversibleSortedList<TKey, TValue> 提供七個建構子多載,涵蓋無參、指定比較器、指定字典、指定容量、指定字典與比較器、指定容量與比較器等所有常見初始化需求。本文逐一解析各建構子的實現邏輯與設計意圖。
static ReversibleSortedList()
{
emptyKeys = new TKey[0];
emptyValues = new TValue[0];
}
採用單例模式提供共享空陣列,避免每個空實例重複配置陣列物件,節省記憶體與 GC 壓力。
public ReversibleSortedList()
{
keys = emptyKeys;
values = emptyValues;
_size = 0;
_sortDirectionComparer = new SortDirectionComparer<TKey>();
_currentSortDirection = _sortDirectionComparer.SortDirection;
}
直接引用靜態空陣列,建立預設升序比較器,零配置開銷。
public ReversibleSortedList(SortDirectionComparer<TKey> comparer) : this()
{
if (comparer != null)
{
_sortDirectionComparer = comparer;
_currentSortDirection = _sortDirectionComparer.SortDirection;
}
}
鏈呼叫無參建構子,再替換比較器。支援外部傳入 IComparer<TKey> 實現完全自訂排序(如忽略大小寫、文化特定排序)。
public ReversibleSortedList(IDictionary<TKey, TValue> dictionary)
: this(dictionary, (SortDirectionComparer<TKey>)null) { }
委派給下一個多載,傳入 null 比較器使用預設排序。
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;
}
直接配置指定大小陣列,適合預知大概元素數量的場景,消除擴容開銷。
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;
}
關鍵步驟:
CopyTo 批次複製鍵值陣列Array.Sort(keys, values, comparer) 同步排序兩平行陣列時間複雜度 O(n log n),一次性完成初始化與排序。
public ReversibleSortedList(int capacity, SortDirectionComparer<TKey> comparer)
: this(comparer)
{
Capacity = capacity; // 觸發容量設定邏輯
}
先建立比較器,再設定容量屬性(內部會配置新陣列並複製現有資料,此處為空陣列故無複製成本)。
原始碼中未直接展示,但 Capacity 屬性設定器、TrimExcess 等方法會內部建立新陣列並複製資料,實現類似複製建構子的功能。
null 檢查、容量非負檢查CopyTo + Array.Sort 替代逐筆 Add七個建構子形成完整的初始化矩陣,滿足從「極輕量空實例」到「大量資料預排序匯入」的全譜系需求。原始碼展現了框架級集合的工程化思維:效能優先、API 正交、資源節制。研讀此類建構子設計,對掌握高品質類別庫開發極具參考價值。