飄過來學C#系列(3)之------泛型

來源:互聯網
上載者:User

標籤:blog   http   ar   使用   for   strong   sp   資料   div   

泛型是程式設計語言的一種特性。允許程式員在強型別程式設計語言中編寫

代碼時定義一些可變部分,那些部分在使用前必須作出指明。各種程式設計語言和其編譯器、運行環境對泛型的支援均不一樣。將型別參數化以達到代碼複用提高軟體開發工作效率的一種資料類型。泛型類是參考型別,是堆對象,主要是引入了型別參數這個概念。

泛型的優點:

效能

實值型別儲存在棧上,參考型別儲存在堆上,.net中很容易把實值型別轉換為參考型別,將一個實值型別轉換為參考型別叫裝箱,反之叫拆箱,裝箱和拆箱操作很容易進行,但是會損失效能.

var list = new ArrayList();list.Add(44);  //裝箱foreach(int item in list){    Console.WriteLine(item);//拆箱}

下面的例子中用List<int>,所以int類在JIT編譯器動態產生的類中使用,不再進行裝箱和拆箱操作.

List<int> list = new List<int>();list.Add(44);//不用裝箱foreach(int item in list){     Console.WriteLine(item);//不用拆箱      }

型別安全

var list = new ArrayList();list.Add(44);list.Add("string");    list.Add(new MyClass());    foreach( int item  in list){     Console.WriteLine(item);//運行報錯}

如果用泛型

List<int> list = new List<int>();list.Add(44);list.Add("string");//無法執行list.Add(new MyClass());//無法執行

這樣錯誤能夠儘早的發現,編譯器就不會編譯這段代碼.

二進位代碼重用

泛型可以定義一次,使用不同的類型執行個體化

var list = new List<int>();
list.Add(44);var stringList = new List<string>();
stringList.Add("string");var classList = new List<Class>();
classList.Add(new Class())

 

飄過來學C#系列(3)之------泛型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.