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

打造可逆向排序的泛型字典類 (九 續):多重建構子完整實作代碼

     編輯:關於C語言

建構子完整代碼


// 指定排序方向
public ReversibleSortedList(SortDirectionComparer<TKey> comparer) : this()
{
    if (comparer != null)
    {
        _sortDirectionComparer = comparer;
        _currentSortDirection = comparer.SortDirection;
    }
}

// 指定初始字典
public ReversibleSortedList(IDictionary<TKey, TValue> dict) 
    : this(dict, (SortDirectionComparer<TKey>)null) { }

// 指定初始容量
public ReversibleSortedList(int capacity)
{
    if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), "需非負數");
    keys = new TKey[capacity];
    values = new TValue[capacity];
    _sortDirectionComparer = new SortDirectionComparer<TKey>();
    _currentSortDirection = _sortDirectionComparer.SortDirection;
}

// 指定字典與排序方向
public ReversibleSortedList(IDictionary<TKey, TValue> dict, SortDirectionComparer<TKey> comparer)
    : this((dict != null) ? 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, _sortDirectionComparer);
    _size = dict.Count;
}

// 指定容量與排序方向
public ReversibleSortedList(int capacity, SortDirectionComparer<TKey> comparer) : this(comparer)
{
    Capacity = capacity; // 呼叫 set 存取子
}

建構子鏈設計避免重複代碼,Array.Sort(keys, values, comparer) 同步排序雙陣列。Capacity 屬性需提供 set 實作 InternalSetCapacity 以支援修剪與擴容。

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