Why covariance and contravariance do not support value type

前端 未结 4 1713
耶瑟儿~
耶瑟儿~ 2020-11-22 00:46

IEnumerable is co-variant but it does not support value type, just only reference type. The below simple code is compiled successfully:

<
4条回答
  •  礼貌的吻别
    2020-11-22 01:10

    Basically, variance applies when the CLR can ensure that it doesn't need to make any representational change to the values. References all look the same - so you can use an IEnumerable as an IEnumerable without any change in representation; the native code itself doesn't need to know what you're doing with the values at all, so long as the infrastructure has guaranteed that it will definitely be valid.

    For value types, that doesn't work - to treat an IEnumerable as an IEnumerable, the code using the sequence would have to know whether to perform a boxing conversion or not.

    You might want to read Eric Lippert's blog post on representation and identity for more on this topic in general.

    EDIT: Having reread Eric's blog post myself, it's at least as much about identity as representation, although the two are linked. In particular:

    This is why covariant and contravariant conversions of interface and delegate types require that all varying type arguments be of reference types. To ensure that a variant reference conversion is always identity-preserving, all of the conversions involving type arguments must also be identity-preserving. The easiest way to ensure that all the non-trivial conversions on type arguments are identity-preserving is to restrict them to be reference conversions.

    提交回复
    热议问题