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

構建可反轉排序的泛型字典 (9/完):完善功能、構造函數重載與測試驗證

     編輯:關於C#

系列回顧

前 8 篇已實現:雙陣列存儲、二分查找插入、自動擴容、自定義比較器、IEnumerable/ICollection/IDictionary 介面、Keys/Values 集合視圖、枚舉器版本檢查。本篇完成最後拼圖:排序方向切換、修剪多餘容量、豐富構造函數。

核心補充功能

1. 動態切換排序方向


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(); // 立即生效

2. 修剪多餘容量


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);
}

3. 完整構造函數族


// 默認:降序、容量 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>,涵蓋:

  • **數據結構**:雙平行陣列 + 二分查找 + 自動擴容(2倍增長)。
  • **排序核心**:SortDirectionComparer 封裝升/降序邏輯,支援運行時切換。
  • **介面實現**:`IDictionary`, `IDictionary`, `ICollection>`, `IEnumerable>` 及非泛型對應介面。
  • **集合視圖**:`Keys`/`Values` 返回 `IList` 唯讀視圖,支援索引、Contains、CopyTo、枚舉。
  • **枚舉器**:結構體實現 `IEnumerator>` + `IDictionaryEnumerator`,版本號檢測並發修改。
  • **工程細節**:構造函數鏈、異常規範、XML 註釋、TrimExcess、序列化友好。

閱讀 .NET Framework 原始碼(SortedDictionary、SortedList、List)將更有深度理解。完整源碼可作為教學案例或生產級擴展基礎。

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