Covariance and Contravariance on the same type argument

后端 未结 7 695
时光取名叫无心
时光取名叫无心 2021-01-02 06:45

The C# spec states that an argument type cannot be both covariant and contravariant at the same time.

This is apparent when creating a covariant or contravariant int

相关标签:
7条回答
  • 2021-01-02 07:14

    Generic type parameters cannot be both covariant and contravariant.

    Why? This has to do with the restrictions which in and out modifiers impose. If we wanted to make our generic type parameter both covariant and contravariant, we would basically say:

    • None of the methods of our interface returns T
    • None of the methods of our interface accepts T

    Which would essentially make our generic interface non-generic.

    I explained it in detail under another question:

    0 讨论(0)
提交回复
热议问题