[讀書筆記]先談C#編程 泛型程式設計的好處

來源:互聯網
上載者:User

泛型最大的4個好處:

1,效能

     分析下面的例子

  ArrayList的Add()方法定義為需要把一個對象作為參數,所以要裝箱一個整數類型。在讀取ArrayList中的值時,要進行拆箱,把對象轉換為整數類型。 裝箱和拆箱操作容易使用,但是效能損失比較大,迭代許多項時尤其如此。

  

CODE 1:ArrayList list = new ArrayList();list.Add(44);    // boxing - covert a value type to a reference typeint i1 = (int)list[0]   //unboxing - covert a reference type to a value typeforeach(int i2 in list){    Console.WriteLine(i2); // unboxing}

 

List<T>類不是用對象,而是在使用時定義類型。在下面的例子中,List<T>類的泛型型別定義為int,所以int類型在JIT編譯器動態產生的類中使用,不再進行裝箱和拆箱操作。

CODE2:List<int> list = new List<int>();list.Add(44);     // no boxing - value types are stored in the List<int>int i1 = list[0];    // no unboxing, no cast neededforeach (int i2 in list){    Console.WriteLine(i2);}

 

2. 型別安全

    理解起來很簡單,就是如果類型不符就會報錯。確保型別安全

3.二進位代碼重用

   泛型允許更好的重用二進位代碼。泛型類可以定義一次,用許多不通的類型執行個體化。不需要像C++模板那樣訪問原始碼。

4. 代碼的擴充

    這個沒看懂啥意思。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.