注意:這樣的調整空間會導致另外開辟內存以重新存放元素。
好,最後的工作就是增加一些構造方法,比如指定排序方向,指定容量 ,以使得這個集合類的使用更為靈活:
//用於指定排序方向的構 造方法
public ReversibleSortedList (SortDirectionComparer<TKey> comparer)
: this()
{
if (comparer != null)
{
this._sortDirectionComparer = comparer;
this._currentSortDirection = _sortDirectionComparer.SortDirection;
}
}
//用於指定字典的構造方法
public ReversibleSortedList(IDictionary<TKey, TValue> dictionary)
: this(dictionary, (SortDirectionComparer<TKey>)null)
{
}
//用於指定初始容量的構造方法
public ReversibleSortedList (int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(
"capacity", "Non-negative number required");
}
this.keys = new TKey [capacity];
this.values = new TValue[capacity];
this._sortDirectionComparer = new SortDirectionComparer<TKey>();
this._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(this.keys, 0);
dictionary.Values.CopyTo(this.values, 0);
Array.Sort<TKey, TValue>(this.keys, this.values,
this._sortDirectionComparer);
this._size = dictionary.Count;
}
//用於指定容量 和排序方向的構造方法
public ReversibleSortedList(int capacity, SortDirectionComparer<TKey> comparer)
: this(comparer)
{
this.Capacity = capacity;
}