[读书笔记]先谈C#编程 泛型编程的好处

泛型最大的4个好处:

1,性能

     分析下面的例子

  ArrayList的Add()方法定义为需要把一个对象作为参数,所以要装箱一个整数类型。在读取ArrayList中的值时,要进行拆箱,把对象转换为整数类型。 装箱和拆箱操作容易使用,但是性能损失比较大,迭代许多项时尤其如此。

  

CODE 1:

ArrayList list = new ArrayList();
list.Add(44);    // boxing - covert a value type to a reference type

int i1 = (int)list[0]   //unboxing - covert a reference type to a value type


foreach(int i2 in list)
{
    Console.WriteLine(i2); // unboxing
}

List<T>类不是用对象,而是在使用时定义类型。在下面的例子中,List<T>类的泛型类型定义为int,所以int类型在JIT编译器动态生成的类中使用,不再进行装箱和拆箱操作。

CODE2:

List<int> list = new List<int>();
list.Add(44);     // no boxing - value types are stored in the List<int>

int i1 = list[0];    // no unboxing, no cast needed

foreach (int i2 in list)
{
    Console.WriteLine(i2);
}

2. 类型安全

    理解起来很简单,就是如果类型不匹配就会报错。确保类型安全

3.二进制代码重用

   泛型允许更好的重用二进制代码。泛型类可以定义一次,用许多不通的类型实例化。不需要像C++模板那样访问源代码。

4. 代码的扩展

    这个没看懂啥意思。

原文地址:https://www.cnblogs.com/herbert/p/1740656.html