Why does C# (4.0) not allow co- and contravariance in generic class types?

前端 未结 3 709
悲哀的现实
悲哀的现实 2020-11-27 07:13

What is the real reason for that limitation? Is it just work that had to be done? Is it conceptually hard? Is it impossible?

Sure, one couldn\'t use

3条回答
  •  隐瞒了意图╮
    2020-11-27 08:12

    If they were permitted, useful 100% type-safe (no internal typecasts) classes or structures could be defined which were covariant with regard to their type T, if their constructor accepted one or more T's or T supplier's. Useful, 100%-type-safe classes or structures could be defined which were contravariant with respect to T if their constructors accepted one or more T consumers. I'm not sure there's much advantage of a class over an interface, beyond the ability to use "new" rather than using a static factory method (most likely from a class whose name is similar to that of the interface), but I can certainly see usage cases for having immutable structures support covariance.

提交回复
热议问题