Definition: When defining generics , we can use where to limit the range of parameters .
Use: When using generics , you must respect the scope of the where restriction parameter , or the compilation will not pass.
Six Types of Constraints:
T: Class (the type argument must be a reference type; This also applies to any class, interface, delegate, or array type.) )
class Myclass<t, u> whereclass /// constraint T parameter must be "reference type {}" The wherestruct /// constraint u parameter must be "value type" {}
T: struct (the type parameter must be a value type.) You can specify any value type other than Nullable. )
class Myclass<t, u> whereclass /// constraint T parameter must be "reference type {}" where struct /// The constraint u parameter must be a value type { }
t:new ()(the type parameter must have a public constructor with no arguments.) When used with other constraints, the new () constraint must be specified last. )
class where New (){ // ...}
t:< base class name >(the type parameter must be the specified base class or derived from the specified base class.) )
Public class employee{} Public class where T:employee
t:< Interface Name >(the type parameter must be the specified interface or implementation of the specified interface.) You can specify multiple interface constraints. The constraint interface can also be generic. )
/// <summary> ///Interface/// </summary> InterfaceIMyInterface {}/// <summary> ///A dictionary type that is defined/// </summary> /// <typeparam name= "TKey" ></typeparam> /// <typeparam name= "Tval" ></typeparam> classDictionary<tkey, tval>wheretkey:icomparable, IEnumerablewhereTval:imyinterface { Public voidAdd (TKey key, Tval val) {}}
t:u(the type parameter provided for T must be a parameter supplied for u or derived from the parameter supplied for U.) which means the parameters of T and U must be the same )
class List<t>{ voidwhere u:t {/*... */ }}
One, can be used for the class:
Public class where t:icomparable {}
Two, can be used for methods:
Public BOOL where T:imyinterface {}
Third, can be used for delegation:
Delegate where New ()
When do you use them in the actual project?
Sometimes when you are working on a project, you need to use generics, and you just want to pass the generic parameters to your scope.
For example, if you want a value type , or a reference type , or a type that inherits to a certain type, or one that matches a certain hook ,
What should you do at this time? You need to use where to limit it.
Reference Documentation:
Https://msdn.microsoft.com/zh-cn/library/d5x73970.aspx
Https://msdn.microsoft.com/zh-cn/library/bb384067.aspx
WHERE (generic type constraint)