Home >Backend Development >C++ >How Does C# 4.0 Handle Generic Covariance and Contravariance?
In -depth understanding of the genetic collaboration and inverter in C# 4.0
In the early version of C#, the generic type does not support collaborative or inverter, which will bring restrictions when dealing with the aggregation of the parent -child relationship. However, C# 4.0 introduced support for these concepts under specific constraints.
The coordination in the interface
The collaborative type allows generic types to accept derivatives as parameters. For the interface, use the "out" keyword specification. For example, if we have an interface , which means that the interface allows only the value of the retrieval type to T. This enables us to return
from the statement to the method of returning. IEnumerable<out T>
IEnumerable<object>
Revelation in the commission IEnumerable<string>
The inverter allows the generic type to accept the base type as the parameter. For commission, use "in" keywords. Consider commission. This means a method of accepting a parameter of T type T. You can now use as , because the method of expecting objects can still work normally when passing the string.
Implement the details Action<in T>
Action<object>
The variance support in Action<string>
C# 4.0 is realized through the function of running (CLR) during public language. The compiler will verify the correct use of the interface and the variance on the entrustment. Specifically, the interface can only use "OUT" for only output parameters, and the entrustment must use "in" for only input parameters (setter).
Make sure the type is safe
Although the difference between the C# 4.0 supporting variance, it is carried out in a type of safe way. The compiler ensures that any code that trys to violate the type constraint will be rejected. This prevents the banana list from being forced to be converted into a fruit list, which is invalid.Summary
C# 4.0 The genetic coordination and inverter in the rejection of the type of the type of the type of fate provides higher flexibility and code reusability. It enables developers to seamlessly use the interface and commission that expresses the relationship between father and son types.
The above is the detailed content of How Does C# 4.0 Handle Generic Covariance and Contravariance?. For more information, please follow other related articles on the PHP Chinese website!