Problem understanding covariance contravariance with generics in C#

后端 未结 2 1862
梦如初夏
梦如初夏 2021-01-30 15:33

I can\'t understand why the following C# code doesn\'t compile.

As you can see, I have a static generic method Something with an IEnumerable parame

2条回答
  •  情歌与酒
    2021-01-30 15:55

    The error message is insufficiently informative, and that is my fault. Sorry about that.

    The problem you are experiencing is a consequence of the fact that covariance only works on reference types.

    You're probably saying "but IA is a reference type" right now. Yes, it is. But you didn't say that T is equal to IA. You said that T is a type which implements IA, and a value type can implement an interface. Therefore we do not know whether covariance will work, and we disallow it.

    If you want covariance to work you have to tell the compiler that the type parameter is a reference type with the class constraint as well as the IA interface constraint.

    The error message really should say that the conversion is not possible because covariance requires a guarantee of reference-type-ness, since that is the fundamental problem.

提交回复
热议问题