similar to a non-generic type, the compiled representation of a generic type is intermediate language (il) instructions and metadata. the representation of the generic type of course also encodes the existence and use of type parameters.
the first time an application creates an instance of a constructed generic type, such as stack<int>, the just-in-time (jit) compiler of the .net common language runtime converts the generic il and metadata to native code, substituting actual types for type parameters in the process. subsequent references to that constructed generic type then use the same native code. the process of creating a specific constructed type from a generic type is known as a generic type instantiation.
the .net common language runtime creates a specialized copy of the native code for each generic type instantiation with a value type, but shares a single copy of the native code for all reference types (since, at the native code level, references are just pointers with the same representation).
commonly, a generic class will do more than just store data based on a type parameter. often, the generic class will want to invoke methods on objects whose type is given by a type parameter. for example, an add method in a dictionary<k,v> class might need to compare keys using a compareto method:
public class dictionary<k,v> { public void add(k key, v value) { ...
if (key.compareto(x) < 0) {...} // error, no compareto method ... } }
since the type argument specified for k could be any type, the only members that can be assumed to exist on the key parameter are those declared by type object, such as equals, gethashcode, and tostring; a compile-time error therefore occurs in the example above. it is of course possible to cast the key parameter to a type that contains a compareto method. for example, the key parameter could be cast to icomparable:
public class dictionary<k,v> { public void add(k key, v value) { ...
if (((icomparable)key).compareto(x) < 0) {...} ... } }
while this solution works, it requires a dynamic type check at run-time, which adds overhead. it furthermore defers error reporting to run-time, throwing an invalidcastexception if a key doesn’t implement icomparable.
to provide stronger compile-time type checking and reduce type casts, c# permits an optional list of constraints to be supplied for each type parameter. a type parameter constraint specifies a requirement that a type must fulfill in order to be used as an argument for that type parameter. constraints are declared using the word where, followed by the name of a type parameter, followed by a list of class or interface types, or the constructor constraint new().
in order for the dictionary<k,v> class to ensure that keys always implement icomparable, the class declaration can specify a constraint for the type parameter k:
public class dictionary<k,v> where k: icomparable { public void add(k key, v value) { ...
if (key.compareto(x) < 0) {...} ... } }
given this declaration the compiler will ensure that any type argument supplied for k is a type that implements icomparable. furthermore, it is no longer necessary to explicitly cast the key parameter to icomparable before calling the compareto method; all members of a type given as a constraint for a type parameter are directly available on values of that type parameter type.
for a given type parameter, it is possible to specify any number of interfaces as constraints, but no more than one class. each constrained type parameter has a separate where clause. in the example below, the type parameter k has two interface constraints, while the type parameter e has a class constraint and a constructor constraint:
public class entitytable<k,e> where k: icomparable<k>, ipersistable where e: entity, new() { public void add(k key, e entity) { ...
if (key.compareto(x) < 0) {...} ... } }
the constructor constraint, new(), in the example above ensures that a type used as a type argument for e has a public, parameterless constructor, and it permits the generic class to use new e() to create instances of that type.
上面例子中的构建约束new(),确保作为类型参数e的类型有一个公共的,无参数的构建函数,且它允许泛型类 使用 new e() 去创建该类型的实例。
type parameter constrains should be used with care. while they provide stronger compile-time type checking and in some cases improve performance, they also restrict the possible uses of a generic type. for example, a generic class list<t> might constrain t to implement icomparable such that the list’s sort method can compare items. however, doing so would preclude use of list<t> for types that don’t implement icomparable, even if the sort method is never actually called in those cases.