Covariance and Contravariance on the same type argument

后端 未结 7 723
时光取名叫无心
时光取名叫无心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 07:04

    Is this limitation simply a language specific constraint or are there deeper, more fundamental reasons based in category theory that would make you not want your type to be both covariant and contravariant?

    No, there is a much simpler reason based in basic logic (or just common sense, whichever you prefer): a statement cannot be both true and not true at the same time.

    Covariance means S <: T ⇒ G <: G and contravariance means S <: T ⇒ G <: G. It should be pretty obvious that these can never be true at the same time.

提交回复
热议问题