欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

編寫高質(zhì)量代碼改善C#程序——使用泛型集合代替非泛型集合(建議20)

 更新時(shí)間:2015年08月14日 11:23:47   作者:JesseLZJ  
這篇文章主要介紹編寫高質(zhì)量的代碼有助于改善C#程序,在開發(fā)過程中集合用的比較多,如何把集合使用好,在開發(fā)過程必須掌握的技巧,下面這篇文章就給大家詳細(xì)介紹編寫高質(zhì)量代碼改善C#程序——使用泛型集合代替非泛型集合(建議20),需要的朋友可以參考下

軟件開發(fā)過程中,不可避免會(huì)用到集合,C#中的集合表現(xiàn)為數(shù)組和若干集合類。不管是數(shù)組還是集合類,它們都有各自的優(yōu)缺點(diǎn)。如何使用好集合是我們?cè)陂_發(fā)過程中必須掌握的技巧。不要小看這些技巧,一旦在開發(fā)中使用了錯(cuò)誤的集合或針對(duì)集合的方法,應(yīng)用程序?qū)?huì)背離你的預(yù)想而運(yùn)行。

建議20:使用泛型集合代替非泛型集合

在建議1中我們知道,如果要讓代碼高效運(yùn)行,應(yīng)該盡量避免裝箱和拆箱,以及盡量減少轉(zhuǎn)型。很遺憾,在微軟提供給我們的第一代集合類型中沒有做到這一點(diǎn),下面我們看ArrayList這個(gè)類的使用情況:

  ArrayList al=new ArrayList();
      al.Add(0);
      al.Add(1);
      al.Add("mike");
      foreach (var item in al)
      {
        Console.WriteLine(item);
      }

上面這段代碼充分演示了我們可以將程序?qū)懙枚嗝丛愀狻?/p>

首先,ArrayList的Add方法接受一個(gè)object參數(shù),所以al.Add(1)首先會(huì)完成一次裝箱;其次,在foreach循環(huán)中,待遍歷到它時(shí),又將完成一次拆箱。

在這段代碼中,整形和字符串作為值類型和引用類型,都會(huì)先被隱式地強(qiáng)制轉(zhuǎn)型為object,然后在foreach循環(huán)中又被轉(zhuǎn)型回來。

同時(shí),這段代碼也是非類型安全的:我們?nèi)籄rrayList同時(shí)存儲(chǔ)了整型和字符串,但是缺少編譯時(shí)的類型檢查。雖然有時(shí)候需要有意這樣去實(shí)現(xiàn),但是更多的時(shí)候,應(yīng)該盡量避免。缺少類型檢查,在運(yùn)行時(shí)會(huì)帶來隱含的Bug。集合類ArrayList如果進(jìn)行如下所示的運(yùn)算,就會(huì)拋出一個(gè)IvalidCastException:          

 ArrayList al=new ArrayList();
      al.Add(0);
      al.Add(1);
      al.Add("mike");
      int t = 0;
      foreach (int item in al)
      {
        t += item;
      }

ArrayList同時(shí)還提供了一個(gè)帶ICollection參數(shù)的構(gòu)造方法,可以直接接收數(shù)組,如下所示:

var intArr = new int[] {0, 1, 2, 3};
ArrayList al=new ArrayList(intArr);

該方法內(nèi)部實(shí)現(xiàn)一樣糟糕,如下所示(構(gòu)造方法內(nèi)部最終調(diào)用了下面的InsertRange方法):

public virtual void InsertRange(int index, ICollection c)
{
  if (c == null)
  {
    throw new ArgumentNullException("c", Environment.GetResourceString("ArgumentNull_Collection"));
  }
  if ((index < 0) || (index > this._size))
  {
    throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_Index"));
  }
  int count = c.Count;
  if (count > 0)
  {
    this.EnsureCapacity(this._size + count);
    if (index < this._size)
    {
      Array.Copy(this._items, index, this._items, index + count, this._size - index);
    }
    object[] array = new object[count];
    c.CopyTo(array, 0);
    array.CopyTo(this._items, index);
    this._size += count;
    this._version++;
  }
}

概括來講,如果對(duì)大型集合進(jìn)行循環(huán)訪問、轉(zhuǎn)型或裝箱和拆箱操作,使用ArrayList這樣的傳統(tǒng)集合對(duì)效率影響會(huì)非常大。鑒于此,微軟提供了對(duì)泛型的支持。泛型使用一對(duì)<>括號(hào)將實(shí)際類型括起來,然后編譯器和運(yùn)行時(shí)會(huì)完成剩余的工作。微軟也不建議大家使用ArrayList這樣的類型了,轉(zhuǎn)而建議使用它們的泛型實(shí)現(xiàn),如List<T>。

注意,非泛型集合在System.Collections命名空間下,對(duì)應(yīng)的泛型集合則在System.Collections.Generic命名空間下。

建議一開始的那段代碼的泛型實(shí)現(xiàn)為:           

List<int> intList = new List<int>();
      intList.Add(1);
      intList.Add(2);
      //intList.Add("mike");
      foreach (var item in intList)
      {
        Console.WriteLine(item);
      }

代碼中被注釋的那一行不會(huì)被編譯通過,因?yàn)椤癿ike"不是整型,這里就體現(xiàn)了類型安全的特點(diǎn)。

下面比較了非泛型集合和泛型集合在運(yùn)行中的效率:

 static void Main(string[] args)
    {
      Console.WriteLine("開始測(cè)試ArrayList:");
      TestBegin();
      TestArrayList();
      TestEnd();
      Console.WriteLine("開始測(cè)試List<T>:");
      TestBegin();
      TestGenericList();
      TestEnd();
    }
    static int collectionCount = 0;
    static Stopwatch watch = null;
    static int testCount = 10000000;
    static void TestBegin()
    {
      GC.Collect();  //強(qiáng)制對(duì)所有代碼進(jìn)行即時(shí)垃圾回收
      GC.WaitForPendingFinalizers(); //掛起線程,執(zhí)行終結(jié)器隊(duì)列中的終結(jié)器(即析構(gòu)方法)
      GC.Collect();  //再次對(duì)所有代碼進(jìn)行垃圾回收,主要包括從終結(jié)器隊(duì)列中出來的對(duì)象
      collectionCount = GC.CollectionCount(0);  //返回在0代碼中執(zhí)行的垃圾回收次數(shù)
      watch = new Stopwatch();
      watch.Start();
    }

    static void TestEnd()
    {
      watch.Stop();
      Console.WriteLine("耗時(shí):" + watch.ElapsedMilliseconds.ToString());
      Console.WriteLine("垃圾回收次數(shù):" + (GC.CollectionCount(0) - collectionCount));
    }

    static void TestArrayList()
    {
      ArrayList al = new ArrayList();
      int temp = 0;
      for (int i = 0; i < testCount; i++)
      {
        al.Add(i);
        temp = (int)al[i];
      }
      al = null;
    }

    static void TestGenericList()
    {
      List<int> listT = new List<int>();
      int temp = 0;
      for (int i = 0; i < testCount; i++)
      {
        listT.Add(i);
        temp = listT[i];
      }
      listT = null;
    }

輸出為:

開始測(cè)試ArrayList:

耗時(shí):2375

垃圾回收次數(shù):26

開始測(cè)試List<T>:

耗時(shí):220

垃圾回收次數(shù):5

以上介紹了編寫高質(zhì)量代碼改善C#程序——使用泛型集合代替非泛型集合(建議20),有關(guān)編寫高質(zhì)量代碼建議1到建議157,本完整會(huì)持續(xù)更新,敬請(qǐng)關(guān)注,謝謝。

相關(guān)文章

最新評(píng)論