C# 4.0 The genetic collaboration and inverter
C# 4.0 introduces support for genetic collaboration and inverter, which makes the genealogy of generic types more flexible. In the early version of C#, trying
to assign to List<string>
will cause the compiler error, although List<object>
can accommodate any object that can be converted to a string. List<string>
) to coordinate, and the input variant type (such as IEnumerable<T>
) is inverted. Action<T>
Coordination allows one type to be used as an alternative to another type in the inheritance hierarchical structure. For example,
can be assigned to, because the string is an object. This is because List<string>
is declared List<object>
, indicating that it can only output the value of the type T. Therefore, as long as is only used for reading value, it is safe to use it as IEnumerable<T>
. IEnumerable<out T>
List<string>
Reverse List<object>
Disposter allows one type to be used as an alternative to another type in the inheritance hierarchical structure. For example, can be assigned to , because objects can receive string as parameters. This is because
is declared, indicating that it can only accept the value of the type T. Therefore, as long as is used only for transmitting value, it is safe to use it as Action<object>
. Action<string>
Action<T>
Implement the details Action<in T>
Action<object>
Action<string>
In C# 4.0, the variance is achieved using CLR's collaborative and inverse support. This makes C# 4.0 support the variance without affecting the type of security.
When the generic type declaration is the output deformation or input deformation, the compiler generates additional IL code to check the variance of the type parameter during runtime. This ensures that coordination and inverting are used in a safe way.
The above is the detailed content of How Does C# 4.0's Generic Covariance and Contravariance Enhance Type Assignment Flexibility?. For more information, please follow other related articles on the PHP Chinese website!