The concept of collaboration and inverter allows to use a collaborative change and accept a super type (for example, assigning
to). However, this behavior does not apply to the value type, such as IEnumerable<T>
. IEnumerable<string>
IEnumerable<object>
Documents point out that this limit is because the variance is only applicable to the principle of reference type. In order to understand the reason, let's explore the concept of boxing and its impact on coordination and inverter. IEnumerable<int>
Value type is stored directly in memory, and there is no logo separation from its value. When the value type is assigned to the reference variable, a process is called the box. In this process, the value type is packaged in an object packaging device, which contains the memory location of the value type. This packaging device allows the type of value to be regarded as the object. Packing and variance
In order to make the coordinating effect, the CLR must ensure that it will not be represented when assigned the reference type to the super type. This is because the use code does not need to know the exact type of the object it is operating. However, for the type, there is no object packaging; the value is directly stored in memory. Therefore, when the value type is assigned to the reference variable, the packing operation is required. This packing operation will be represented by the value, introducing a layer of indirectability.
The identification and the square difference
The identification is the ability to maintain the same identifier when assigned the object to the base type or derived type. In the coordinated change, the identification of the CLR requesting object is retained. However, for the type of value, the packing and box removal operation may unexpectedly change the identification of the object. This violates the characteristics of the synergy conversion logo.
Therefore, in order to ensure the effectiveness of the identification and reference, the CLR only limits the collaboration and inverter to the reference type.
The above is the detailed content of Why Aren't Value Types Covariant or Contravariant in C#?. For more information, please follow other related articles on the PHP Chinese website!