泛型(C# 编程指南)Generics (C# Programming Guide)

C# 语言和公共语言运行时 (CLR) 的 2.0 版本中添加了泛型。Generics were added to version 2.0 of the C# language and the common language runtime (CLR). 泛型将类型参数的概念引入 .NET Framework,这样就可以设计具有以下特征的类和方法:在客户端代码声明并初始化这些类和方法之前,这些类和方法会延迟指定一个或多个类型。Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. 例如,通过使用泛型类型参数 T,可以编写其他客户端代码能够使用的单个类,而不会产生运行时转换或装箱操作的成本或风险,如下所示:For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:

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

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

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

泛型概述Generics Overview

  • 使用泛型类型可以最大限度地重用代码、保护类型安全性以及提高性能。Use generic types to maximize code reuse, type safety, and performance.

  • 泛型最常见的用途是创建集合类。The most common use of generics is to create collection classes.

  • .NET Framework 类库在 System.Collections.Generic 命名空间中包含几个新的泛型集合类。The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. 应尽可能使用这些类来代替某些类,如 System.Collections 命名空间中的 ArrayListThese should be used whenever possible instead of classes such as ArrayList in the System.Collections namespace.

  • 可以创建自己的泛型接口、泛型类、泛型方法、泛型事件和泛型委托。You can create your own generic interfaces, classes, methods, events and delegates.

  • 可以对泛型类进行约束以访问特定数据类型的方法。Generic classes may be constrained to enable access to methods on particular data types.

  • 在泛型数据类型中所用类型的信息可在运行时通过使用反射来获取。Information on the types that are used in a generic data type may be obtained at run-time by using reflection.

更多相关信息:For more information:

C# 语言规范C# Language Specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification.

请参阅See Also

System.Collections.Generic
C# 编程指南C# Programming Guide
类型Types
<typeparam><typeparam>
<typeparamref><typeparamref>
.NET 中的泛型Generics in .NET