泛型类型参数 -(C# 编程指南)Generic type parameters (C# Programming Guide)

在泛型类型或方法定义中,类型参数是在其创建泛型类型的一个实例时,客户端指定的特定类型的占位符。In a generic type or method definition, a type parameter is a placeholder for a specific type that a client specifies when they create an instance of the generic type. 泛型类(例如泛型介绍中列出的 GenericList<T>)无法按原样使用,因为它不是真正的类型;它更像是类型的蓝图。A generic class, such as GenericList<T> listed in Introduction to Generics, cannot be used as-is because it is not really a type; it is more like a blueprint for a type. 若要使用 GenericList<T>,客户端代码必须通过指定尖括号内的类型参数来声明并实例化构造类型。To use GenericList<T>, client code must declare and instantiate a constructed type by specifying a type argument inside the angle brackets. 此特定类的类型参数可以是编译器可识别的任何类型。The type argument for this particular class can be any type recognized by the compiler. 可创建任意数量的构造类型实例,其中每个使用不同的类型参数,如下所示:Any number of constructed type instances can be created, each one using a different type argument, as follows:

GenericList<float> list1 = new GenericList<float>();
GenericList<ExampleClass> list2 = new GenericList<ExampleClass>();
GenericList<ExampleStruct> list3 = new GenericList<ExampleStruct>();

GenericList<T> 的每个实例中,类中出现的每个 T 在运行时均会被替换为类型参数。In each of these instances of GenericList<T>, every occurrence of T in the class is substituted at run time with the type argument. 通过这种替换,我们已通过使用单个类定义创建了三个单独的类型安全的有效对象。By means of this substitution, we have created three separate type-safe and efficient objects using a single class definition. 有关 CLR 如何执行此替换的详细信息,请参阅运行时中的泛型For more information on how this substitution is performed by the CLR, see Generics in the Run Time.

类型参数命名指南Type parameter naming guidelines

  • 请使用描述性名称命名泛型类型参数 ,除非单个字母名称完全具有自我说明性且描述性名称不会增加任何作用。Do name generic type parameters with descriptive names, unless a single letter name is completely self explanatory and a descriptive name would not add value.

    public interface ISessionChannel<TSession> { /*...*/ }
    public delegate TOutput Converter<TInput, TOutput>(TInput from);
    public class List<T> { /*...*/ }
    
  • 对具有单个字母类型参数的类型,考虑使用 T 作为类型参数名称 。Consider using T as the type parameter name for types with one single letter type parameter.

    public int IComparer<T>() { return 0; }
    public delegate bool Predicate<T>(T item);
    public struct Nullable<T> where T : struct { /*...*/ }
    
  • 在类型参数描述性名称前添加前缀 "T" 。Do prefix descriptive type parameter names with "T".

    public interface ISessionChannel<TSession>
    {
        TSession Session { get; }
    }
    
  • 请考虑在参数名称中指示出类型参数的约束 。Consider indicating constraints placed on a type parameter in the name of parameter. 例如,约束为 ISession 的参数可命名为 TSessionFor example, a parameter constrained to ISession may be called TSession.

可以使用代码分析规则 CA1715 确保恰当地命名类型参数。The code analysis rule CA1715 can be used to ensure that type parameters are named appropriately.

请参阅See also