Recommendation 34: Setting constraints for generic parameters
The word "constraint" may cause ambiguity, and some would argue that restricting the use of generic parameter constraints is the opposite of the actual situation. A generic parameter without a "constraint" has a limited effect, but a "constraint" allows a generic parameter to have more behavior and properties.
Looking at the code below, we find that parameter T1 or parameter t2 only have properties and behavior of object, so you can almost no longer manipulate them in a method:
class Salarycomputer { public int cpmpare<t> (t T1, T T2) { return 0 ; }} class Salary { public int basesalary {get ; Span style= "color: #0000ff;" >set ;} public int Bonus {get ; set
However, after adding the constraints, we will find that the parameters T1 and T2 become a useful object. Because of the corresponding type assigned to it, T1 and T2 are now a salary, and in the method it has the properties basesalary and bonus, the code is as follows:
classSalarycomputer { Public intCpmpare<t> (t T1, T T2)whereT:salary {if(t1. Basesalary >T2. Basesalary) {return 1; } if(t1. Basesalary = =T2. Basesalary) {return 0; } return-1; } }
So what constraints can you specify for generics? As shown below:
1) Specify that the parameter is a value type (except Nullable):
Public void where struct { }
2) specify that the parameter is a reference type:
Public void where class {}publicvoidwhere t:salary {}
Note that object cannot be used to constrain.
3) Specifies that the parameter has a public construction method with no parameters:
Public void where New () { }
Note that the CLR currently supports only the constraints of the parameterless constructor method.
4) The specified parameter must be the specified base class, or derived from the specified base class.
5) Specify that the parameter must be a specified interface, or implement the specified interface.
6) Specifies that the parameter type provided by T must be a parameter supplied for u, or derived from the parameter supplied for u:
class Sample<u> { publicvoidwhere t:u { } }
7) You can apply more than one constraint to a parameter of the same type, and the constraint itself can be a generic type.
In programming, you should consider setting constraints on generic parameters, which make generic parameters a tangible "object" that has the behavior and properties we want, not just an object.
Refer to MSDN: Constraints on type parameters (C # Programming Guide)
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 34: Setting constraints on generic parameters