Home >Backend Development >C++ >Why Are Value Types Invariant in C# Generics?
C#generic medium -value types of unsatisfactory type
The variance in the generics allows the type to inherit the collaboration or inverting of its parameters. However, these mechanisms are not applicable for value types. To understand this limit, we need to study the concept of packing and its impact on type security.
Declaration is a change. Coordination allows derived types to replace the base type, such as
and. However, the value type is not the case. Consider the following code:
IEnumerable<T>
IEnumerable<string>
This code can cause compilation errors because the value type is considered immutable. The variance is only suitable for reference type. The reason is the complexity of the box. IEnumerable<object>
<code class="language-csharp">IEnumerable<int> intList = new List<int>(); IEnumerable<object> objList = intList;</code>variables, the box is executed when runtime, and a
packaging device is created around
. This allows value types to be considered a reference type in some cases.
int
However, in terms of collaborative and inverse, boxing will bring serious types of security issues. If the value type is allowed, the derived type may include different data from its base type. This may cause accidental behavior and potential data damage. object
int
For example, may include objects with different object
indicating forms. When these objects are visited, they must be discharged to the original
In order to maintain type security, the CLR limit the variance to the reference type. This can ensure that the form is consistent and conversion between different types will not cause data integrity.
The above is the detailed content of Why Are Value Types Invariant in C# Generics?. For more information, please follow other related articles on the PHP Chinese website!