下面的代码比较容易理解:

// Declare the generic class.
public class GenericList<T>
{
    void Add(T input) { }
}
class TestGenericList
{
    private class ExampleClass { }
    static void Main()
    {
        // Declare a list of type int.
        GenericList<int> list1 = new GenericList<int>();

        // Declare a list of type string.
        GenericList<string> list2 = new GenericList<string>();

        // Declare a list of type ExampleClass.
        GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
    }
}

  1. 泛型类和泛型方法同时具备可重用性、类型安全和效率,这是非泛型类和非泛型方法无法具备的。泛型通常用与集合以及作用于集合的方法一起使用。
  • 效率高。在使用非泛型集合类时,添加到该类中的任何引用或值类型都将隐式地向上强制转换为object .如果项是值类型,则必须在将其添加到列表中时进行装箱操作,检索时取消装箱操作
  • 编译时类型检查。在隐式强制转换为object 时,编译时不会出错,但是稍后运行时可能导致一个错误。

// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();

// No boxing, no casting:
list1.Add(3);

// Compile-time error:
// list1.Add("It is raining in Redmond.");

posted on 2011-03-22 00:48  默斋  阅读(123)  评论(0编辑  收藏  举报