.NET泛型基础

来源:互联网 发布:八毛门事件 知乎 编辑:程序博客网 时间:2024/05/22 07:08
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
泛型较为广泛地被讨论,这里写到的只是作为新手的入门级认识。

泛型最常应用于集合类。

泛型的一个显而易见的优点在于可以在许多操作中避免强制转换或装箱操作的成本或风险,拿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);

}

}
http://www.cnblogs.com/KissKnife/archive/2006/08/26/486807.html

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>