.NET泛型基礎

來源:互聯網
上載者:User
泛型較為廣泛地被討論,這裡寫到的只是作為新手的入門級認識。

泛型最常應用於集合類。

泛型的一個顯而易見的優點在於可以在許多操作中避免強制轉換或裝箱操作的成本或風險,拿ArrayList這個集合類來說,為了達到其通用性,集合元素都將向上轉換為object類型,對於實值型別,更是有裝箱拆箱的成本:

static void Main(string[] args)

{

ArrayList al = new ArrayList();

al.Add(1);

}

在IL中是:

IL_0008: ldc.i4.1

IL_0009: box [mscorlib]System.Int32

IL_000e: callvirt instance int32 [mscorlib]System.Collections.ArrayList::Add(object)

box操作就是裝箱,具體過程是把實值型別從棧中彈出,放入堆中,同時把在堆中的地址壓入到棧中,頻繁出現這樣的操作,成本比較大。

所以在2.0中,遇到以上的應用,應該使用泛型集合類List<T>:

static void Main(string[] args)

{

List<int> l = new List<int>();

l.Add(1);

}

 

另一個比較常用的泛型集合類是Dictionary<T,T>,用於儲存索引值對:

static void Main(string[] args)

{

Dictionary<int, string> dict = new Dictionary<int, string>();

dict.Add(1, "SomeBook1");

dict.Add(2, "SomeBook2");

dict.Add(3, "SomeBook3");

 

Console.WriteLine(dict[2]);//output:SomeBook2

dict[2] = "SomeCD1";//modify

Console.WriteLine(dict[2]);//output:SomeCD1

 

dict.Remove(2);//delete

 

foreach (KeyValuePair<int, string> kv in dict)

{

Console.WriteLine("Key = {0}, Value = {1}",kv.Key, kv.Value);

}

}

聯繫我們

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