inforasc

美好的每一天

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
1、命名空间:
  System.Collections.Generic(程序集:mscorlib)
2、描述:
  1)、表示可通过索引访问的对象的强类型列表;提供用于对列表进行搜索、排序和操作的方法。
  2)、是ArrayList类的泛型等效类。
  3)、可以使用一个整数索引访问此集合中的元素;索引从 零 开始。
  4)、可以接收null空引用(VB中的Nothing)。
  5)、允许重复元素
3、创建及初始化:
  List<string> myList = new List<string>();//初始Capacity为 零
  List<string> myList2 = new List<string>(30); //初始Capacity为 30
  List<string> myList3 = new List<string>(new string[] { "1", "a", "2", "b" });//初始Capacity 为 4,并且元素已被复制
4、Capacity与Count
  1)、Capacity在需要调整大小之前可存储的元素数;Count实际存储的元素数。
  2)、Capacity总是大于或者等于Count
  通过Reflector查看add()方法对Capacity和Count的影响:
  在 List<T>中:
    private T[] items;
    private int _size;
    public int Count{
      get{
        return this._size;
      }
    }
    public int Capacity
    {
      get{
        return this._items.Length;
      }
      set{
        //......
      }
    }
  当我们调用Add方法添加元素的时候,其内部实现为:
  public void Add(T item)
  {
    if(this._size == this._items.Length)
    {
      this.EnsureCapacity(this._size + 1); //扩充Capatity
    }
    this._items[this._size++] = item;
    //.......
  }
  private void EnsureCapacity(int min)
  {
      if (this._items.Length < min)
      {
          int num = (this._items.Length == 0) ? 4 : (this._items.Length * 2);
          if (num < min)
          {
              num = min;
          }
          this.Capacity = num;
      }
  }
  至此,Capacity和Count之间的异同可以一目了然。
  通过TrimExcess 方法可以使Capacity 等于 Count;
  TrimExcess的内部实现:
  public void TrimExcess()
  {
       int num = (int) (this._items.Length * 0.9);
       if (this._size < num)
       {
            this.Capacity = this._size;
       }
  }
  在这里,我们也可以明白MSDN上的这句话:“如果列表大于容量的 90%,则 TrimExcess 方法将不执行任何操作”。
5、遍历元素:
  foreach (string s in myList)
  {
      Console.WriteLine("\nEl: {0}", s);
  }
6、插入元素 By Insert:
  myList.Insert(index, "VB"); //插入到指定的索引处(index不能大于Capacity-1)
7、移除元素 By Remove:
  myList.Remove("C#");//移除特定对象的第一个匹配项:如有两个“C#”,则移除一个既索引小的那个
  
posted on 2009-10-04 08:22  inforasc  阅读(8225)  评论(3编辑  收藏  举报