Variability is often used in generic interfaces and generic delegates
In Contravariance, out covariant
From list<string> to list<object> called covariant (string derives from object, it is reasonable to turn a string into object, it is reasonable for subclasses to replace the parent class)
It is unreasonable to go from list<object> to List<string>, which is called inversion (by turning the object into a string and turning the parent class into a subclass, which is called inversion).
1. Invert Code Masking
Static voidMain (string[] args) {Icovariant<Object> iobj =NewSample<object>(); Icovariant<String> ISTR =NewSample<string>(); //You can assign ISTR to Iobj because//The Icovariant interface is covariant. //iobj = ISTR;ISTR =iobj;//Convert from Object type to string type, parent class to subclass is Contravariant console.readline (); } //covariant interface. Interfaceicovariant<inchR> { } //extending covariant interface. Interfaceiextcovariant<inchR>: icovariant<r> { } //implementing covariant interface. classSample<r>: icovariant<r> {}
2. Co-change Demo
Static voidMain (string[] args) {Icovariant<Object> iobj =NewSample<object>(); Icovariant<String> ISTR =NewSample<string>(); //You can assign ISTR to Iobj because//The Icovariant interface is covariant. //iobj = ISTR;Iobj =ISTR; //From string to type Object, sub-type to parent (the Richter substitution principle) is covariant Console.ReadLine (); } //covariant interface. Interfaceicovariant< outR> { } //extending covariant interface. Interfaceiextcovariant< outR>: icovariant<r> { } //implementing covariant interface. classSample<r>: icovariant<r> {}
Covariant out and Contravariance in C #