When defining generic classes, you canCodeYou can apply restrictions on the type types used for type parameters during class instantiation. If the client code attempts to instantiate a class using a type not allowed by a certain constraint, a compile-time error will occur. These restrictions are called constraints. The constraint is specified using the where context keyword. The following table lists five types of constraints:
Constraints |
Description |
T: Structure |
The type parameter must be a value type. You can specify any value type except nullable. For more information, see use a void type (C # programming guide ). |
T: Class |
The type parameter must be a reference type, including any class, interface, delegate, or array type. |
T: New () |
The type parameter must have a public constructor without parameters. When used with other constraints, the new () constraint must be specified at the end. |
T: <Base Class Name> |
The type parameter must be a specified base class or derived from the specified base class. |
T: <Interface Name> |
The type parameter must be a specified interface or implement the specified interface. Multiple interface constraints can be specified. The constraint interface can also be generic. |
T: u |
The type parameter provided for T must be provided for U or derived from U. This is called the bare type constraint. |
Reasons for restrictions
If you want to check an item in the generic list to determine whether it is valid, or compare it with another item, the compiler must ensure that the operators or methods to be called by the compiler are supported by any type of parameters that may be specified by the client code. This guarantee is obtained by applying one or more constraints to the generic class definition. For example, a base class constraint tells the compiler that only objects of this type or objects derived from this type can be used as type parameters. Once the compiler has this guarantee, it can allow calling methods of this type in generic classes. The constraint is applied using the context keyword where.
Unbound type parameter
Type parameters without constraints (such as public classes)Sampleclass <t> {}
T) is called an unbound type parameter. Unbound type parameters have the following rules:
Not available! = And = operators, because they cannot be supported by specific type parameters.
They can be converted back and forth between them and system. object, or they can be explicitly converted to any interface type.
You can compare them with null. When you compare unbound parameters with null, if the type parameter is of the value type, the comparison always returns false.
Bare type constraints
The generic type parameters used as constraints are called Bare type constraints. When a member function with its own type parameters needs to constrain this parameter to include type parameters, the bare type constraints are useful.