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, IEnumerator
  {
    private ReversibleSortedList<K, V> _ReversibleSortedList;
    private K key;
    private V value;
    private int index;
    private int version;
    internal Enumerator(ReversibleSortedList<K, V> ReversibleSortedList)
    {
      this._ReversibleSortedList = ReversibleSortedList;
      this.index = 0;
      this.version = this._ReversibleSortedList.version;
      this.key = default(K);
      this.value = default(V);
    }
    public void Dispose()
    {
      this.index = 0;
      this.key = default(K);
      this.value = default(V);
    }
    object IDictionaryEnumerator.Key
    {
      get
      {
        if ((this.index == 0) ||
          (this.index == (this._ReversibleSortedList.Count + 1)))
        {
          throw new InvalidOperationException(
              "Enumeration operation cannot occur.");
        }
        return this.key;
      }
    }
    public bool MoveNext()
    {
      if (this.version != this._ReversibleSortedList.version)
      {
        throw new InvalidOperationException(
            "Enumeration failed version check");
      }
      if (this.index < this._ReversibleSortedList.Count)
      {
        this.key = this._ReversibleSortedList.keys[this.index];
        this.value = this._ReversibleSortedList.values[this.index];
        this.index++;
        return true;
      }
      this.index = this._ReversibleSortedList.Count + 1;
      this.key = default(K);
      this.value = default(V);
      return false;
    }
    DictionaryEntry IDictionaryEnumerator.Entry
    {
      get
      {
        if ((this.index == 0) ||
          (this.index == (this._ReversibleSortedList.Count + 1)))
        {
          throw new InvalidOperationException(
              "Enumeration operation cannot happen.");
        }
        return new DictionaryEntry(this.key, this.value);
      }
    }
    public KeyValuePair<K, V> Current
    {
      get
      {
        return new KeyValuePair<K, V>(this.key, this.value);
      }
    }
    object IEnumerator.Current
    {
      get
      {
        if ((this.index == 0) ||
          (this.index == (this._ReversibleSortedList.Count + 1)))
        {
          throw new InvalidOperationException(
              "Enumeration operation cannot occur");
        }
        return new DictionaryEntry(this.key, this.value);
      }
    }
    object IDictionaryEnumerator.Value
    {
      get
      {
        if ((this.index == 0) ||
          (this.index == (this._ReversibleSortedList.Count + 1)))
        {
          throw new InvalidOperationException(
              "Enumeration operation cannot occur");
        }
        return this.value;
      }
    }
    void IEnumerator.Reset()
    {
      if (this.version != this._ReversibleSortedList.version)
      {
        throw new InvalidOperationException(
            "Enumeration version check failed");
      }
      this.index = 0;
      this.key = default(K);
      this.value = default(V);
    }
  }
  #endregion // Enumerator <K, V>
  KeyListK,V#region KeyList<K,V>
  [Serializable]
  private sealed class KeyList<K, V> : IList<K>, ICollection<K>,
                        IEnumerable<K>, ICollection, IEnumerable
  {
    // Methods
    internal KeyList(ReversibleSortedList<K, V> dictionary)
    {
      this._dict = dictionary;
    }
    public void Add(K key)
    {
      throw new NotSupportedException("Add is unsupported");
    }
    public void Clear()
    {
      throw new NotSupportedException("Clear is unsupported");
    }
    public bool Contains(K key)
    {
      return this._dict.ContainsKey(key);
    }
    public void CopyTo(K[] array, int arrayIndex)
    {
      Array.Copy(this._dict.keys, 0, array, arrayIndex, this._dict.Count);
    }
    public IEnumerator<K> GetEnumerator()
    {
      return new
         ReversibleSortedList<K, V>.ReversibleSortedListKeyEnumerator(
                           this._dict);
    }
    public int IndexOf(K key)
    {
      if (key == null)
      {
        throw new ArgumentNullException("key");
      }
      int num1 = Array.BinarySearch<K>(this._dict.keys, 0,
                          this._dict.Count, key,
                          this._dict._sortDirectionComparer);
      if (num1 >= 0)
      {
        return num1;
      }
      return -1;
    }
    public void Insert(int index, K value)
    {
      throw new NotSupportedException("Insert is unsupported");
    }
    public bool Remove(K key)
    {
      //throw new NotSupportedException("Remove is unsupported");
      return false;
    }
    public void RemoveAt(int index)
    {
      throw new NotSupportedException("RemoveAt is unsupported");
    }
    void ICollection.CopyTo(Array array, int arrayIndex)
    {
      if ((array != null) && (array.Rank != 1))
      {
        throw new ArgumentException(
           "MultiDimensional arrays are not unsupported");
      }
      try
      {
        Array.Copy(this._dict.keys, 0, array, arrayIndex,
              this._dict.Count);
      }
      catch (ArrayTypeMismatchException atme)
      {
        throw new ArgumentException("InvalidArrayType", atme);
      }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
      return new
          ReversibleSortedList<K, V>.ReversibleSortedListKeyEnumerator(
                                      this._dict);
    }
    // Properties
    public int Count
    {
      get
      {
        return this._dict._size;
      }
    }
    public bool IsReadOnly
    {
      get
      {
        return true;
      }
    }
    public K this[int index]
    {
      get
      {
        return this._dict.GetKey(index);
      }
      set
      {
        throw new NotSupportedException("Set is an unsupported operation");
      }
    }
    bool ICollection.IsSynchronized
    {
      get
      {
        return false;
      }
    }
    object ICollection.SyncRoot
    {
      get
      {
        return this._dict;
      }
    }
    // Fields
    private ReversibleSortedList<K, V> _dict;
  }
  #endregion // KeyList<K,V>
  ReversibleSortedListKeyEnumerator definition#region ReversibleSortedListKeyEnumerator definition
  [Serializable]
  private sealed class ReversibleSortedListKeyEnumerator : IEnumerator<TKey>,
                               IDisposable,
                               IEnumerator
  {
    // Methods
    internal ReversibleSortedListKeyEnumerator(
        ReversibleSortedList<TKey, TValue> ReversibleSortedList)
    {
      this._ReversibleSortedList = ReversibleSortedList;
      this.version = ReversibleSortedList.version;
    }
    public void Dispose()
    {
      this.index = 0;
      this.currentKey = default(TKey);
    }
    public bool MoveNext()
    {
      if (this.version != this._ReversibleSortedList.version)
      {
        throw new InvalidOperationException(
          "Enumeration failed version check");
      }
      if (this.index < this._ReversibleSortedList.Count)
      {
        this.currentKey = this._ReversibleSortedList.keys[this.index];
        this.index++;
        return true;
      }
      this.index = this._ReversibleSortedList.Count + 1;
      this.currentKey = default(TKey);
      return false;
    }
    void IEnumerator.Reset()
    {
      if (this.version != this._ReversibleSortedList.version)
      {
        throw new InvalidOperationException(
          "Enumeration failed version check");
      }
      this.index = 0;
      this.currentKey = default(TKey);
    }
    // Properties
    public TKey Current
    {
      get
      {
        return this.currentKey;
      }
    }
    object IEnumerator.Current
    {
      get
      {
        if ((this.index == 0) || (this.index ==
            (this._ReversibleSortedList.Count + 1)))
        {
          throw new InvalidOperationException(
              "Enumeration operation could not occur");
        }
        return this.currentKey;
      }
    }
    // Fields
    private ReversibleSortedList<TKey, TValue> _ReversibleSortedList;
    private TKey currentKey;
    private int index;
    private int version;
  }
  #endregion //ReversibleSortedListKeyEnumerator definition
  ReversibleSortedListValueEnumerator definition#region ReversibleSortedListValueEnumerator definition
  [Serializable]
  private sealed class ReversibleSortedListValueEnumerator : IEnumerator<TValue>,
                                IDisposable,
                                IEnumerator
  {
    // Methods
    internal ReversibleSortedListValueEnumerator(
             ReversibleSortedList<TKey, TValue> ReversibleSortedList)
    {
      this._ReversibleSortedList = ReversibleSortedList;
      this.version = ReversibleSortedList.version;
    }
    public void Dispose()
    {
      this.index = 0;
      this.currentValue = default(TValue);
    }
    public bool MoveNext()
    {
      if (this.version != this._ReversibleSortedList.version)
      {
        throw new InvalidOperationException(
          "Enumeration failed version check");
      }
      if (this.index < this._ReversibleSortedList.Count)
      {
        this.currentValue = this._ReversibleSortedList.values[this.index];
        this.index++;
        return true;
      }
      this.index = this._ReversibleSortedList.Count + 1;
      this.currentValue = default(TValue);
      return false;
    }
    void IEnumerator.Reset()
    {
      if (this.version != this._ReversibleSortedList.version)
      {
        throw new InvalidOperationException(
          "Enumeration failed version check");
      }
      this.index = 0;
      this.currentValue = default(TValue);
    }
    // Properties
    public TValue Current
    {
      get
      {
        return this.currentValue;
      }
    }
    object IEnumerator.Current
    {
      get
      {
        if ((this.index == 0) || (this.index ==
            (this._ReversibleSortedList.Count + 1)))
        {
          throw new InvalidOperationException(
              "Enumeration operation could not occur");
        }
        return this.currentValue;
      }
    }
    // Fields
    private ReversibleSortedList<TKey, TValue> _ReversibleSortedList;
    private TValue currentValue;
    private int index;
    private int version;
  }
  #endregion //ReversibleSortedListValueEnumerator
  ValueList K, V definition#region ValueList <K, V> definition
  [Serializable]
  private sealed class ValueList<K, V> : IList<V>, ICollection<V>,
                         IEnumerable<V>, ICollection, IEnumerable
  {
    // Methods
    internal ValueList(ReversibleSortedList<K, V> dictionary)
    {
      this._dict = dictionary;
    }
    public void Add(V key)
    {
      throw new NotSupportedException("Add is not supported");
    }
    public void Clear()
    {
      throw new NotSupportedException("Clear is not supported");
    }
    public bool Contains(V value)
    {
      return this._dict.ContainsValue(value);
    }
    public void CopyTo(V[] array, int arrayIndex)
    {
      Array.Copy(this._dict.values, 0, array, arrayIndex, this._dict.Count);
    }
    public IEnumerator<V> GetEnumerator()
    {
      return new
          ReversibleSortedList<K, V>.ReversibleSortedListValueEnumerator(
                                    this._dict);
    }
    public int IndexOf(V value)
    {
      return Array.IndexOf<V>(this._dict.values, value, 0, this._dict.Count);
    }
    public void Insert(int index, V value)
    {
      throw new NotSupportedException("Insert is not supported");
    }
    public bool Remove(V value)
    {
      //throw new NotSupportedException("Remove is not supported");
      return false;
    }
    public void RemoveAt(int index)
    {
      throw new NotSupportedException("RemoveAt is not supported");
    }
    void ICollection.CopyTo(Array array, int arrayIndex)
    {
      if ((array != null) && (array.Rank != 1))
      {
        throw new ArgumentException(
          "MultiDimensional arrays not supported");
      }
      try
      {
        Array.Copy(this._dict.values, 0, array, arrayIndex,
              this._dict.Count);
      }
      catch (ArrayTypeMismatchException atme)
      {
        throw new ArgumentException("Invalid array type", atme);
      }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
      return new
          ReversibleSortedList<K, V>.ReversibleSortedListValueEnumerator(
                                   this._dict);
    }
    // Properties
    public int Count
    {
      get
      {
        return this._dict._size;
      }
    }
    public bool IsReadOnly
    {
      get
      {
        return true;
      }
    }
    public V this[int index]
    {
      get
      {
        return this._dict.GetByIndex(index);
      }
      set
      {
        throw new NotSupportedException("Set by indexer is not supported");
      }
    }
    bool ICollection.IsSynchronized
    {
      get
      {
        return false;
      }
    }
    object ICollection.SyncRoot
    {
      get
      {
        return this._dict;
      }
    }
    // Fields
    private ReversibleSortedList<K, V> _dict;
  }
  #endregion // ValueList <TKey, TValue> definition
  #endregion // Nested types
}

在SortedList混合使用了数组和列表语法,这使得以任一方式访问数据变得非常容易。ReversibleSortedList<T>中数据也可以使用键/值对或索引来访问。和SortedList一样,它不允许重复键。另外不管值是引用类型还是值类型都可以为null,但键不行。ReversibleSortedList<T>的默认容量是16,这和SortedList是一样的。里面的项可以使用foreach循环进行迭代,它返回KeyValuePair,但这是只读的,迭代语法禁止在读取列表时进行元素的更新或删除,否则就是无效的迭代器。

时间: 2025-01-01 23:26:06

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

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.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 ((i