inforasc

美好的每一天

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
1、命名空间:
System.Collections.Generic(程序集:mscorlib)
2、描述:
1)、同一任意类型的实例的大小可变的后进先出 (LIFO) 集合。
2)、Stack作为数组来实现。
3)、Stack容量是指可以保存的元素数;向Stack添加元素时,重新分配内部数组,根据需要自动增大容量。
4)、可以接收null空引用(VB中的Nothing
3、创建及初始化:
1)、Stack<string> myStack = new Stack<string>();//初始化实例,该实例为空并且具有默认初始容量
  2)、Stack<string> myStack2 = new Stack<string>(Int32 capacity /*5*/);//capacity,初始可包含元素数,
    必须大于等于 0;Count 为 5

  3)、 Stack<string> myStack3 = new Stack<string>(IEnumerable<T> collection /*new string[] { "1",
    "2", "3" }*/); //从指定的集合中复制元素;collection 不能为null;Count为 3
4、Count:
  通过Reflector查看Push()、Pop()、Peek()方法对Count的影响:
  在Stack<T>中:
  private T[] _array;
  private static T[] _emptyArray;
  private const int _defaultCapacity = 4;
  private int _size;
  public int Count
  {
      get
      {
          return this._size;
      }
  }
  当调用Push()方法把元素压入时:
  public void Push(T item)
  {
    //分配新的空间,其中this._array在构造函数中,已经进行了初始化
    //在第一次压入元素时,初始默认内部数组的长度为4
      if (this._size == this._array.Length)
      {
          T[] destinationArray = new T[(this._array.Length == 0) ? 4 : (2 * this._array.Length)];
          Array.Copy(this._array, 0, destinationArray, 0, this._size);
          this._array = destinationArray;
      }
      this._array[this._size++] = item;//通过修改this._size,使得Count发生变化
      //......
  }
  当调用Pop()方法时:
  public T Pop()
  {
      if (this._size == 0)
      {
          ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);
      }
        //......
      T local = this._array[--this._size];//通过修改this._size,使得Count发生变化
      this._array[this._size] = default(T);
      return local;
  }
  所以当Stack为空时,调用Pop(),出现InvalidOperationException异常
  public T Peek()
  {
      if (this._size == 0)
      {
          ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EmptyStack);
      }
      return this._array[this._size - 1];
  }
   所以当Stack为空时,调用Peek(),也会出现InvalidOperationException异常
   Peek()只是查看Stack中的元素,而不修改Stack,而Pop()会修改Stack。
5、遍历元素:
   Stack<string> myStack2 = new Stack<string>(new string[] { "1", "2", "3","4","5" });
       Console.WriteLine("Count:{0}", myStack2.Count);
       foreach (string stack in myStack2)
       {
         Console.WriteLine("stack El:{0}", stack);
   }
posted on 2009-10-05 11:11  inforasc  阅读(993)  评论(0编辑  收藏  举报