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> where t:class///constraint T parameter must be "reference type {}" where u:struct///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> where t:class///constraint T parameter must be "reference type {}" where u:struct///constraint U parameter must be "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 employeelist<t> where T:employee, IEmployee, System.icomparable<t>, 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 genericlist<t> 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> interface imyinterface { } //<summary >/// definition of a dictionary type///</summary>// <typeparam name= "TKey" ></typeparam> // <typeparam name= "Tval" ></typeparam> class Dictionary<tkey, tval> where TKey: IComparable, IEnumerable where tval:imyinterface {public void Add (TKey key, Tval val) { }< c18/>}
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>{ void Add<u> (list<u> items) where U:t {/*...*/}}
One, can be used for the class:
public class mygenericclass<t> where t:icomparable {}
Two, can be used for methods:
public bool Mymethod<t> (T-t) where t:imyinterface {}
Third, can be used for delegation:
Delegate T mydelegate<t> () where T:new ()
C # WHERE (generic type constraint)