class Program10 { static void Main(string[] args) { //为什么使用泛型?? //早期net framework版本中 // The .NET Framework 1.1 way to create a list: System.Collections.ArrayList list1 = new System.Collections.ArrayList(); list1.Add(3); list1.Add(105); System.Collections.ArrayList list2 = new System.Collections.ArrayList(); list2.Add("It is raining in Redmond."); list2.Add("It is snowing in the mountains."); //1、添加到 ArrayList 的任何引用或值类型均隐式向上转换为 Object。 //如果项为值类型,将它们添加到列表时必须将其装箱,检索它们时必须取消装箱。 //转换与装箱 /取消装箱这两种操作都会降低性能;在必须循环访问大型集合的方案中,装箱与取消装箱的影响非常大。 //2、另一局限是缺少编译时类型检查;由于 ArrayList 将所有内容都转换为 Object,因此在编译时无法阻止客户端代码执行如下操作: System.Collections.ArrayList list = new System.Collections.ArrayList(); // Add an integer to the list. list.Add(3); // Add a string to the list. This will compile, but may cause an error later. list.Add("It is raining in Redmond."); int t = 0; // This causes an InvalidCastException to be returned. foreach (int x in list) { t += x; } //解决方法:使用List<T>来代替ArrayList // The .NET Framework 2.0 way to create a list List<int> list12 = new List<int>(); // No boxing, no casting: list12.Add(3); // Compile-time error: // list1.Add("It is raining in Redmond."); } }
泛型:(一)为什么造出泛型这个东西?
猜你喜欢
转载自www.cnblogs.com/25miao/p/9863155.html
今日推荐
周排行