Home >Backend Development >C++ >Covariance vs. Contravariance: How Do They Differ in Programming?
In -depth understanding of collaboration and inverting: The key differences in programming
Coordination and inverter are two vital concepts in programming. They define how the functions are applied to different types of objects to ensure type security and flexibility.
Cooperation: Keep assignment compatibility
Coordination is suitable for mapping functions that maintain the compatibility of objects. This means that if the object of the type X can be assigned to the object of the type Y, the result of applying the mapping function to X can always be assigned to the result of applying the function to Y.
For example, consider a set of animals, including Animal, Tiger, FRUIT and Banana. By defining a mapping function from Animal to IenuMerable, we get the following types:
<code>{ Animal, Tiger, Fruit, Banana } → { IEnumerable<Animal>, IEnumerable<Tiger>, IEnumerable<Fruit>, IEnumerable<Banana> }</code>and INUMERABLE
⇒ INUMERABLE
Different from the coordination, the inverter reverses the assignment compatibility relationship. This means that if the object of the type X can be assigned to the object of the type Y, the result of applying the mapping function to Y can be assigned to the result of the application of the function to X. Consider the collection of IComparable type:
In C#, we observe the following compatible relationship:
<code>{ IComparable<Tiger>, IComparable<Animal>, IComparable<Fruit>, IComparable<Banana> } → { IC<Tiger>, IC<Animal>, IC<Fruit>, IC<Banana> }</code>The application mapping function reverses the direction of compatibility. As a result, IC
⇐ ic
, IC<code>Animal ⇒ Tiger Tiger ⇒ Tiger Banana ⇒ Banana Fruit ⇒ Banana Fruit ⇒ Fruit</code>⇐ ic
, and so on. This behavior ensures that the device that can compare Animal can compare the Tiger, otherwise it is not the other.
The above is the detailed content of Covariance vs. Contravariance: How Do They Differ in Programming?. For more information, please follow other related articles on the PHP Chinese website!