Problem understanding covariance contravariance with generics in C#

后端 未结 2 1861
梦如初夏
梦如初夏 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.

    0 讨论(0)
  • 2021-01-30 16:18

    I just wanted to complement Eric's excellent insider answer with a code example for those that may not be that familiar with generic constraints.

    Change Something's signature like this: The class constraint has to come first.

    public static IList<T> Something<T>(IEnumerable<T> foo) where T : class, IA
    
    0 讨论(0)
提交回复
热议问题