Covariance and contravariance: practical applications
Implementing covariance and contravariance in actual scenarios can enhance the flexibility and reusability of code. Here is a simplified example:
Covariant:
Covariant interfaces define output parameters that allow assignment of derived types to less derived types. For example:
<code class="language-c#">public interface ICovariant<out T> { } public class Covariant<T> : ICovariant<T> { } public class Fruit { } public class Apple : Fruit { }</code>
Here, ICovariant<Fruit>
can be assigned to ICovariant<Apple>
because Apple is a subtype of Fruit. Covariance allows us to store different types of data without casting, making the code more concise and versatile.
IContravariant:
Contravariant interface defines input parameters, allowing assignment of less derived types to more derived types. For example:
<code class="language-c#">public interface IContravariant<in T> { } public class Contravariant<T> : IContravariant<T> { }</code>
IContravariant<Apple>
can be assigned to IContravariant<Fruit>
because Fruit is a supertype of Apple. Contravariance allows accepting different types of input parameters while ensuring consistent behavior.
Example:
The following code demonstrates the use of covariance and contravariance:
<code class="language-c#">public class TheInsAndOuts { public void Covariance() { ICovariant<Fruit> fruit = new Covariant<Fruit>(); ICovariant<Apple> apple = new Covariant<Apple>(); Covariance(fruit); Covariance(apple); // 通过协变允许从 Apple 向 Fruit 上转型 } public void Contravariance() { IContravariant<Fruit> fruit = new Contravariant<Fruit>(); IContravariant<Apple> apple = new Contravariant<Apple>(); Contravariant(fruit); // 通过逆变允许从 Fruit 向 Apple 下转型 Contravariant(apple); } public void Covariant(ICovariant<Fruit> fruit) { } public void Contravariant(IContravariant<Apple> apple) { } }</code>
Summary:
Covariance and contravariance enable developers to create flexible and reusable code by allowing compatible type assignments. They extend the functionality of inheritance and facilitate data processing and parameter passing between objects of different types.
The above is the detailed content of How Do Covariance and Contravariance Enhance Code Flexibility and Reusability?. For more information, please follow other related articles on the PHP Chinese website!