前 8 篇已實現:雙陣列存儲、二分查找插入、自動擴容、自定義比較器、IEnumerable/ICollection/IDictionary 介面、Keys/Values 集合視圖、枚舉器版本檢查。本篇完成最後拼圖:排序方向切換、修剪多餘容量、豐富構造函數。
private ListSortDirection _currentDirection = ListSortDirection.Descending;
public SortDirectionComparer Comparer { get; private set; }
public void Sort()
{
if (_currentDirection != Comparer.SortDirection)
{
// 物理反轉鍵值陣列,O(n)
Array.Reverse(_keys, 0, _size);
Array.Reverse(_values, 0, _size);
_currentDirection = Comparer.SortDirection;
_version++;
}
}
使用方式:
var dict = new ReversibleSortedList();
dict.Comparer.SortDirection = ListSortDirection.Ascending;
dict.Sort(); // 立即生效
public void TrimExcess()
{
int threshold = (int)(_keys.Length * 0.9);
if (_size < threshold)
Capacity = _size; // 觸發 InternalSetCapacity 重新分配
}
public int Capacity
{
get => _keys.Length;
set => InternalSetCapacity(value, true);
}
// 默認:降序、容量 0
public ReversibleSortedList() : this(0, null) { }
// 指定比較器(排序方向)
public ReversibleSortedList(SortDirectionComparer comparer)
: this(0, comparer) { }
// 指定初始容量
public ReversibleSortedList(int capacity)
: this(capacity, null) { }
// 指定字典初始化(複製數據並排序)
public ReversibleSortedList(IDictionary dict)
: this(dict, null) { }
// 指定容量 + 比較器
public ReversibleSortedList(int capacity, SortDirectionComparer comparer)
{
if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity));
_keys = new TKey[capacity];
_values = new TValue[capacity];
Comparer = comparer ?? new SortDirectionComparer();
_currentDirection = Comparer.SortDirection;
}
// 指定字典 + 比較器(核心構造函數)
public ReversibleSortedList(IDictionary dict, SortDirectionComparer comparer)
: this(dict?.Count ?? 0, comparer)
{
if (dict == null) throw new ArgumentNullException(nameof(dict));
dict.Keys.CopyTo(_keys, 0);
dict.Values.CopyTo(_values, 0);
Array.Sort(_keys, _values, Comparer);
_size = dict.Count;
}
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("初始降序:");
foreach (var kv in rs) Console.WriteLine($"{kv.Key} {kv.Value}");
// 輸出: 6 d, 5 e, 4 f, 3 a, 2 c, 1 b
Console.WriteLine("\n切換升序:");
rs.Comparer.SortDirection = ListSortDirection.Ascending;
rs.Sort();
foreach (var kv in rs) Console.WriteLine($"{kv.Key} {kv.Value}");
// 輸出: 1 b, 2 c, 3 a, 4 f, 5 e, 6 d
Console.WriteLine($"\n容量: {rs.Capacity}, 數量: {rs.Count}");
rs.TrimExcess();
Console.WriteLine($"TrimExcess 後容量: {rs.Capacity}");
}
從零手寫一個功能完整的 ReversibleSortedList<TKey,TValue>,涵蓋:
SortDirectionComparer 封裝升/降序邏輯,支援運行時切換。閱讀 .NET Framework 原始碼(SortedDictionary、SortedList、List)將更有深度理解。完整源碼可作為教學案例或生產級擴展基礎。