泛型较为广泛地被讨论,这里写到的只是作为新手的入门级认识。 泛型最常应用于集合类。 泛型的一个显而易见的优点在于可以在许多操作中避免强制转换或装箱操作的成本或风险,拿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:
static void Main(string[] args) { List l = new List(); l.Add(1); } 另一个比较常用的泛型集合类是Dictionary,用于保存键值对: static void Main(string[] args) { Dictionary dict = new Dictionary(); 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 kv in dict) { Console.WriteLine("Key = {0}, Value = {1}",kv.Key, kv.Value); } } http://www.cnblogs.com/KissKnife/archive/2006/08/26/486807.html 泛型较为广泛地被讨论,这里写到的只是作为新手的入门级认识。 泛型最常应用于集合类。 泛型的一个显而易见的优点在于可以在许多操作中避免强制转换或装箱操作的成本或风险,拿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:
static void Main(string[] args) { List l = new List(); l.Add(1); } 另一个比较常用的泛型集合类是Dictionary,用于保存键值对: static void Main(string[] args) { Dictionary dict = new Dictionary(); dict.Add(1, "SomeBook1"); dict.Add(2, "SomeBook2"); dict.Add(3, "SomeBook3"); Console.WriteLine(dict[2]);//output:SomeBook2
|