Recommendation 45: Specifying contravariance for generic type parameters
Contravariance refers to a method's parameters can be a base class for a delegate or a generic interface's parameter type. Common delegates that support contravariance in FCL4.0 are:
Func<int T,out tresult>
Predicate<in t>
Common delegates are:
Icomparer<in t>
The following example shows the benefits of specifying the inverse of a generic type parameter:
classProgram {Static voidMain () {Programmer P=NewProgrammer {Name ="Mike" }; Manager m=NewManager {Name ="Steve" }; Test (P, m); } Static voidTest<t> (imycomparable<t>T1, T T2) { //omitted } } Public Interfaceimycomparable<inchT> { intCompare (T other); } Public classEmployee:imycomparable<employee> { Public stringName {Get;Set; } Public intCompare (Employee other) {returnName.compareto (Other. Name); } } Public classProgrammer:employee, imycomparable<programmer> { Public intCompare (Programmer other) {returnName.compareto (Other. Name); } } Public classManager:employee {}
In the above example, if the IN keyword is not specified for the generic parameter T of the interface imycomparable, a test (P,M) compilation error will result. Because of the introduction of the inverse of the interface, this allows the method test to support more scenarios. This should always be noted in the actual encoding of the version after FCL4.0.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
"Go" writing high-quality Code 157 recommendations for improving C # programs--recommendation 45: Specifying contravariance for generic type parameters