Recommendation 43: Make the generic parameter in the interface support covariant
In addition to the use of generic parameter-compatible interfaces, as mentioned in the previous recommendation, there is another way to support covariance by adding the Out keyword to the generic declarations in the interface, as follows:
Interface isalary< out t> // use out keyword { void pay (); }
Static void Main (string[] args) { isalarynew basesalarycounter<programmer>(); IsalaryNew basesalarycounter<manager>(); Printsalary (s); Printsalary (t); } Static void Printsalary (isalary<employee> s) // usage correct { s.pay (); }
This code cannot be compiled before FCL4.0, because ienumerable<t> this interface is not declared as Ienumerable<out t> in the FCL;:
static void Main () {IList <Programmer> programmers = new list< ; Programmer> (); IList <Manager> managers = new list<manager>(); Printpersonname (programmers); Printpersonname (managers); static void Printpersonname ( Ienumerable<employee> persons) { foreach (Employee person in persons) {Console.WriteLine (person. Name); } }
FCL4.0 has modified many interfaces to support covariance, such as Ienumerable<out t>, Ienumerator<out t>, Iquerable<out t>, and so on. Because Ienumerable<out t> now supports covariance, the previous code works well in FCL4.0.
In our own code, if you are writing a generic interface, it is recommended that you add the Out keyword unless you determine that the generic parameter in the interface does not involve a variant. Covariance increases the scope of use of the interface and has little side effects.
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 43: Make generic parameters in interfaces support covariant