C#泛型秘诀(5.2)

私有方法#region 私有方法

private void EnsureCapacity(int min)
  {
  int num1 = (this.keys.Length == 0) ? 4 : (this.keys.Length * 2);
  if (num1 < min)
  {
  num1 = min;
  }
  this.InternalSetCapacity(num1, false);
  }
  //返回指定索引的值
  private TValue GetByIndex(int index)
  {
  if ((index < 0) || (index >= this._size))
  {
  throw new ArgumentOutOfRangeException("index", "Index out of range");
  }
  return this.values[index];
  }
  //返回指定索引的键
  private TKey GetKey(int index)
  {
  if ((index < 0) || (index >= this._size))
  {
  throw new ArgumentOutOfRangeException("index", "Index out of range");
  }
  return this.keys[index];
  }
  private KeyList<TKey, TValue> GetKeyListHelper()
  {
    if (this.keyList == null)
    {
      this.keyList = new KeyList<TKey, TValue>(this);
    }
    return this.keyList;
  }
  private ValueList<TKey, TValue> GetValueListHelper()
  {
    if (this.valueList == null)
    {
      this.valueList = new ValueList<TKey, TValue>(this);
    }
    return this.valueList;
  }
  //在指定位置插入元素
  private void Insert(int index, TKey key, TValue value)
  {
    if (this._size == this.keys.Length)
    {
      this.EnsureCapacity(this._size + 1);
    }
    if (index < this._size)
    {
      Array.Copy(this.keys, index, this.keys, (int)(index + 1),
             (int)(this._size - index));
      Array.Copy(this.values, index, this.values, (int)(index + 1),
             (int)(this._size - index));
    }
    this.keys[index] = key;
    this.values[index] = value;
    this._size++;
    this.version++;
  }
  private void InternalSetCapacity(int value, bool updateVersion)
  {
    if (value != this.keys.Length)
    {
      if (value < this._size)
      {
        throw new ArgumentOutOfRangeException(
          "value", "Too small capacity");
      }
      if (value > 0)
      {
        TKey[] localArray1 = new TKey[value];
        TValue[] localArray2 = new TValue[value];
        if (this._size > 0)
        {
          Array.Copy(this.keys, 0, localArray1, 0, this._size);
          Array.Copy(this.values, 0, localArray2, 0, this._size);
        }
        this.keys = localArray1;
        this.values = localArray2;
      }
      else
      {
        this.keys = ReversibleSortedList<TKey, TValue>.emptyKeys;
        this.values = ReversibleSortedList<TKey, TValue>.emptyValues;
      }
      if (updateVersion)
      {
        this.version++;
      }
    }
  }
  private static bool IsCompatibleKey(object key)
  {
    if (key.Equals(null))
    {
      throw new ArgumentNullException("key");
    }
    return (key is TKey);
  }
  //显式接口成员实现
  void ICollection<KeyValuePair<TKey, TValue>>.Add(
                      KeyValuePair<TKey, TValue> keyValuePair)
  {
    this.Add(keyValuePair.Key, keyValuePair.Value);
  }
  //显式接口成员实现
  bool ICollection<KeyValuePair<TKey, TValue>>.Contains(
                         KeyValuePair<TKey, TValue> keyValuePair)
  {
    int num1 = this.IndexOfKey(keyValuePair.Key);
    if ((num1 >= 0) && EqualityComparer<TValue>.Default.Equals(this.values[num1],
                                  keyValuePair.Value))
    {
      return true;
    }
    return false;
  }
  //显式接口成员实现
  void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(
    KeyValuePair<TKey,TValue>[] array, int arrayIndex)
  {
    if (array == null)
    {
      throw new ArgumentNullException("array");
    }
    if ((arrayIndex < 0) || (arrayIndex > array.Length))
    {
      throw new ArgumentOutOfRangeException(
         "arrayIndex", "Need a non-negative number");
    }
    if ((array.Length - arrayIndex) < this.Count)
    {
      throw new ArgumentException("ArrayPlusOffTooSmall");
    }
    for (int num1 = 0; num1 < this.Count; num1++)
    {
      KeyValuePair<TKey, TValue> pair1;
      pair1 = new KeyValuePair<TKey, TValue>(
            this.keys[num1], this.values[num1]);
      array[arrayIndex + num1] = pair1;
    }
  }
  //显式接口成员实现
  bool ICollection<KeyValuePair<TKey, TValue>>.Remove(
    KeyValuePair<TKey, TValue> keyValuePair)
  {
    int num1 = this.IndexOfKey(keyValuePair.Key);
    if ((num1 >= 0) && EqualityComparer<TValue>.Default.Equals(
      this.values[num1], keyValuePair.Value))
    {
      this.RemoveAt(num1);
      return true;
    }
    return false;
  }
  IEnumerator<KeyValuePair<TKey, TValue>>
     IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
  {
    return new ReversibleSortedList<TKey, TValue>.Enumerator<TKey, TValue>(
          this);
  }
  //显式接口成员实现
  void ICollection.CopyTo(Array array, int arrayIndex)
  {
    if (array == null)
    {
      throw new ArgumentNullException("array");
    }
    if (array.Rank != 1)
    {
      throw new ArgumentException(
        "MultiDimensional array copies are not supported");
    }
    if (array.GetLowerBound(0) != 0)
    {
      throw new ArgumentException("A non-zero lower bound was provided");
    }
    if ((arrayIndex < 0) || (arrayIndex > array.Length))
    {
      throw new ArgumentOutOfRangeException(
        "arrayIndex", "Need non negative number");
    }
    if ((array.Length - arrayIndex) < this.Count)
    {
      throw new ArgumentException("Array plus the offset is too small");
    }
    KeyValuePair<TKey, TValue>[] pairArray1 =
       array as KeyValuePair<TKey, TValue>[];
    if (pairArray1 != null)
    {
      for (int num1 = 0; num1 < this.Count; num1++)
      {
        pairArray1[num1 + arrayIndex] =
          new KeyValuePair<TKey, TValue>(this.keys[num1],
          this.values[num1]);
      }
    }
    else
    {
      object[] objArray1 = array as object[];
      if (objArray1 == null)
      {
        throw new ArgumentException("Invalid array type");
      }
      try
      {
        for (int num2 = 0; num2 < this.Count; num2++)
        {
          objArray1[num2 + arrayIndex] =
              new KeyValuePair<TKey, TValue>(this.keys[num2],
                                this.values[num2]);
        }
      }
      catch (ArrayTypeMismatchException)
      {
        throw new ArgumentException("Invalid array type");
      }
    }
  }
  //显式接口成员实现
  void IDictionary.Add(object key, object value)
  {
    ReversibleSortedList<TKey, TValue>.VerifyKey(key);
    ReversibleSortedList<TKey, TValue>.VerifyValueType(value);
    this.Add((TKey)key, (TValue)value);
  }
  //显式接口成员实现
  bool IDictionary.Contains(object key)
  {
    if (ReversibleSortedList<TKey, TValue>.IsCompatibleKey(key))
    {
      return this.ContainsKey((TKey)key);
    }
    return false;
  }
  //显式接口成员实现
  IDictionaryEnumerator IDictionary.GetEnumerator()
  {
    return new ReversibleSortedList<TKey, TValue>.Enumerator<TKey, TValue>(
        this);
  }
  //显式接口成员实现
  void IDictionary.Remove(object key)
  {
    if (ReversibleSortedList<TKey, TValue>.IsCompatibleKey(key))
    {
      this.Remove((TKey)key);
    }
  }
  //显式接口成员实现
  IEnumerator IEnumerable.GetEnumerator()
  {
    return new ReversibleSortedList<TKey, TValue>.Enumerator<TKey, TValue>(
        this);
  }
  private static void VerifyKey(object key)
  {
    if (key.Equals(null))
    {
      throw new ArgumentNullException("key");
    }
    if (!(key is TKey))
    {
      throw new ArgumentException(
        "Argument passed is of wrong type", "key");
    }
  }
  private static void VerifyValueType(object value)
  {
    if (!(value is TValue) && ((value != null) || typeof(TValue).IsValueType))
    {
      throw new ArgumentException(
        "Argument passed is of wrong type", "value");
    }
  }
  #endregion // Private methods
  Public Properties#region Public Properties
  public int Capacity
  {
    get
    {
      return this.keys.Length;
    }
    set
    {
      this.InternalSetCapacity(value, true);
    }
  }
  public SortDirectionComparer<TKey> Comparer
  {
    get
    {
      return this._sortDirectionComparer;
    }
  }
  public int Count
  {
    get
    {
      return this._size;
    }
  }
  public TValue this[TKey key]
  {
    get
    {
      TValue local1;
      int num1 = this.IndexOfKey(key);
      if (num1 >= 0)
      {
        return this.values[num1];
      }
      else
      {
        //throw new KeyNotFoundException();
        local1 = default(TValue);
        return local1;
      }
    }
    set
    {
      if (key == null)
      {
        throw new ArgumentNullException("key");
      }
      int num1 = Array.BinarySearch<TKey>(this.keys, 0, this._size, key,
                            this._sortDirectionComparer);
      if (num1 >= 0)
      {
        this.values[num1] = value;
        this.version++;
      }
      else
      {
        this.Insert(~num1, key, value);
      }
    }
  }
  public IList<TKey> Keys
  {
    get
    {
      return this.GetKeyListHelper();
    }
  }
  public IList<TValue> Values
  {
    get
    {
      return this.GetValueListHelper();
    }
  }
  #endregion // Public Properties
  Private Properties#region Private Properties
  bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
  {
    get
    {
      return false;
    }
  }
  ICollection<TKey> IDictionary<TKey, TValue>.Keys
  {
    get
    {
      return this.GetKeyListHelper();
    }
  }
  ICollection<TValue> IDictionary<TKey, TValue>.Values
  {
    get
    {
      return this.GetValueListHelper();
    }
  }
  bool ICollection.IsSynchronized
  {
    get
    {
      return false;
    }
  }
  object ICollection.SyncRoot
  {
    get
    {
      return this;
    }
  }
  bool IDictionary.IsFixedSize
  {
    get
    {
      return false;
    }
  }
  bool IDictionary.IsReadOnly
  {
    get
    {
      return false;
    }
  }
  object IDictionary.this[object key]
  {
    get
    {
      if (ReversibleSortedList<TKey, TValue>.IsCompatibleKey(key))
      {
        int num1 = this.IndexOfKey((TKey)key);
        if (num1 >= 0)
        {
          return this.values[num1];
        }
      }
      return null;
    }
    set
    {
      ReversibleSortedList<TKey, TValue>.VerifyKey(key);
      ReversibleSortedList<TKey, TValue>.VerifyValueType(value);
      this[(TKey)key] = (TValue)value;
    }
  }
  ICollection IDictionary.Keys
  {
    get
    {
      return this.GetKeyListHelper();
    }
  }
  ICollection IDictionary.Values
  {
    get
    {
      return this.GetValueListHelper();
    }
  }
  #endregion // Private properties
  Fields#region Fields
  private const int _defaultCapacity = 4;
  private int _size;
  //private IComparer<TKey> comparer;
  private static TKey[] emptyKeys;
  private static TValue[] emptyValues;
  private KeyList<TKey, TValue> keyList;
  private TKey[] keys;
  private ValueList<TKey, TValue> valueList;
  private TValue[] values;
  private int version;
  // Declare comparison object.
  private SortDirectionComparer<TKey> _sortDirectionComparer = null;
  // Default to ascending.
  private ListSortDirection _currentSortDirection = ListSortDirection.Descending;
  #endregion

时间: 2024-12-03 08:02:50

C#泛型秘诀(5.2)的相关文章

C#泛型秘诀(8完)

4.13 初始化泛型变量为它们的默认值 问题 您的泛型类包含一个变量,它的类型和类中定义的类型参数一样.在构造泛型类时,您希望这个变量被初始化为它的默认值. 解决方案 简单地使用default关键字把变量初始化为它的默认值: public class DefaultValueExample<T> { T data = default(T); public bool IsDefaultData() { T temp = default(T); if (temp.Equals(data)) { r

C#泛型秘诀(2)

4.3 获取泛型的类型 问题 您需要在运行时获得一个泛型类型实例的Type对象. 解决方案 在使用typeof操作符时提供类型参数:使用类型参数实例化的泛型类型,用GetType()方法. 声明一个一般类型和一个泛型类型如下: public class Simple { public Simple() { } } public class SimpleGeneric<T> { public SimpleGeneric() { } } 使用typeof操作符和简单类型的名称就可以在运行时获得简单

C#泛型秘诀(1)

4.0 介绍 泛型,一个期待已久的功能,随着C# 2.0版本编译器的到来最终出现.泛型是一个非常有用的功能,它使得您的代码变得精简而富有效率.这些将在秘诀4.1进行详细讲述.泛型的到来使得您可以编写更为强大的应用程序,但这需要正确地使用它.如果您考虑把ArrayList,Queue,Stack和Hashtable对象转变为使用相应的泛型版本,可以阅读秘诀4.4,4.5和4.10.当您阅读过后,会发现这种转变不一定简单,甚至有可能会不再打算进行转变. 本章的另外一些秘诀涉及到.NET Framew

C#泛型秘诀(7)

4.11 在泛型字典类中使用foreach 问题 您希望在实现了System. Collections.Generic.IDictionary接口的类型枚举元素,如System.Collections.Generic.Dictionary 或 System.Collections.Generic.SortedList. 解决方案 最简单的方法是在foreach循环中使用KeyValuePair结构体: // 创建字典对象并填充. Dictionary<int, string> myString

C#泛型秘诀(6)

4.9 使用泛型创建只读集合 问题 您希望类中的一个集合里的信息可以被外界访问,但不希望用户改变这个集合. 解决方案 使用ReadOnlyCollection<T>包装就很容易实现只读的集合类.例子如,Lottery类包含了中奖号码,它可以被访问,但不允许被改变: public class Lottery { // 创建一个列表. List<int> _numbers = null; public Lottery() { // 初始化内部列表 _numbers = new List

C#泛型秘诀(5.1)

4.8 反转Sorted List里的内容 问题 您希望在数组和列表类型中可以反转sorted list里的内容同时又维持SortedList和SortedList<T>类原来的功能.无论是SortedList还是泛型SortedList<T>类都直接提供了完成这个功能的方法而又不需要重填列表. 解决方案 ReversibleSortedList<TKey, TValue>类提供了这些功能,它基于SortedList<TKey, TValue>类,所以拥有相

C#泛型秘诀(4)

4.6 链表的实现 问题 您需要链表数据结构,这样就可以很容易地添加和删除元素. 解决方案 使用泛型LinkedList<T>类.下面的方法创建了一个LinkedList<T>类,并往链表对象中添加节点,然后使用了几种方法从链表节点中获得信息. public static void UseLinkedList() { // 创建一个LinkedList 对象. LinkedList<TodoItem> todoList = new LinkedList<TodoI

C#泛型秘诀(3)

4.5 使用相应的泛型版本替换Stack和Queue 问题 您希望通过将所有Stack和Queue对象替换为相应的泛型版本以提高应用程序的效率,并使得代码更易于使用.当结构体或其他值类型存储在这些数据结构中时,会导致装箱/拆箱操作,这时就需要这么做. 解决方案 使用System.Collections.Generic.Stack和System.Collections.Generic.Queue对象来替换现有的System.Collections.Stack和System.Collections.

C#泛型秘诀(5.3)

Nested Types#region Nested Types Enumerator K, V#region Enumerator <K, V> [Serializable, StructLayout(LayoutKind.Sequential)] private struct Enumerator<K, V> : IEnumerator<KeyValuePair<K, V>>, IDisposable, IDictionaryEnumerator, IE