Covariance and contravariance: understand the difference between "input" and "output"
Covariance and contravariance are concepts in programming that involve how generic types are assigned or accessed from inherited types or types related to them.
Covariance: output position
Covariance allows a more general (or "bigger") type to be used in place of a more specific type when the primitive type is used only as an output value. For example, a list of fruits can be treated as a list of bananas, since there are no restrictions on converting a more specific type to a more general type:
<code>List<水果> 水果列表 = new List<水果>(); 水果列表.Add(new 香蕉()); // 有效,因为香蕉是水果</code>
Inversion: input position
Contravariance allows a more specific (or "smaller") type to be replaced by a more general type when the original type is used only as an input value. This is because more specific types can be safely narrowed down to more general types:
<code>MyInterface<基类> 基类接口 = new MyInterface<派生类>(); // 有效,因为派生类是基类</code>
"Input" and "Output" notation
The "in" and "out" keywords can be used in a generic interface definition to specify whether a generic type parameter represents an output location or an input location.
By specifying "in" or "out", the compiler can perform a safe cast operation without explicit conversion.
Practical example
Consider a generic interface that takes a type parameter as a parameter:
<code>interface MyInterface<T> { void Process(T value); }</code>
If you use inversion to implement this interface:
<code>interface MyInterface<in T> { void Process(T value); }</code>
This means that any object of any derived class can be passed as a parameter to the Process method. This is useful when the logic in a method only requires the base class type regardless of the actual object type.
On the other hand, if you implement the interface using covariance:
<code>interface MyInterface<out T> { T GetValue(); }</code>
This means that any object of any base class can be returned from the GetValue method. This is useful when a method returns a more general type that can be safely converted to various specific types.
The above is the detailed content of What's the Difference Between Covariance and Contravariance in Programming?. For more information, please follow other related articles on the PHP Chinese website!