Why does variance in .NET 4 only support link types?

.NET 4 supports joint and contravariance. However, only reference types are supported, not value types. Why is this?

+2
source share
3 answers

Basically, the CLR should know that it can treat the value of the source type as the value of the target type without performing any additional conversions - just like that, the bit pattern for the source value must be valid as the target value. Views must be the same. Otherwise, the CLR will need additional information to properly convert at the right time.

- . ( :).

+7

; . ,

Func<int> f1 = ()=>2;
Func<object> f2 = f1;
object o1 = f1();
object o2 = f2();

, . ; :

object o1 = BoxIntegerToObject(f1());

, , o2, int. ? f2, . f2, f2 f1, f1 , unboxed int.

, , , , , , . Func<int> Func<object>.

+3

Both forms of variance are defined in terms of inheritance: value types are not inherited.

+2
source

Source: https://habr.com/ru/post/1610193/


All Articles