且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以同时具有协变和逆变的类型,即可以与子类型和超类型完全互换/互换吗?

更新时间:2022-11-22 20:02:42

不,您不能那样做。

假设这是合法的。您制作了 IFoo< Giraffe> 。由于IFoo在T中是协变的,因此可以通过类型安全的引用转换将其转换为 IFoo< object> 。由于它是互变的,因此可以将其转换为 IFoo< Banana> IFoo< T> 有什么可能的语义,以便能够通过引用转换将IFoo of Giraffes转换为Bananas IFoo是有意义的?长颈鹿和香蕉除了参考类型外没有其他共同点。您不可能在 IFoo< Banana> 上有一个返回香蕉的方法,因为它实际上可能是 IFoo< Giraffe> $的实现。 c $ c>;实现的作者如何知道要分发香蕉?出于相同的原因,您可能无法在 IFoo< Banana> 上使用采用香蕉的方法。 IFoo< Giraffe> 的实现者希望您递给他一头长颈鹿。

Suppose that were legal. You make an IFoo<Giraffe>. Since IFoo is covariant in T, you can convert it via typesafe reference conversion to IFoo<object>. Since it is contravariant, you can convert that to IFoo<Banana>. What possible semantics are there for IFoo<T> such that it makes sense to be able to convert an IFoo of Giraffes to an IFoo of Bananas via reference conversion? Giraffes and Bananas have nothing in common other than being reference types. You cannot possibly have a method on IFoo<Banana> that returns a Banana, because it might actually be an implementation of IFoo<Giraffe>; how would the author of the implementation know to hand out a Banana? You cannot possibly have a method on IFoo<Banana> that takes a Banana for the same reason; the implementor of IFoo<Giraffe> is expecting you to hand him a Giraffe.

这是另一种看待方式它:

Here's another way of looking at it:


  • 在T中意味着(大致) T仅出现在输入位置。

  • 输出T表示(大致) T仅出现在输出位置。

因此, in out T的意思是……什么?正如我们已经看到的,它仅表示 T根本不在任何方法或属性中出现。 在T中创建永不使用T的泛型类型有什么意义?

Therefore "in out T" would mean... what? As we've seen already, it can only mean "T does not appear at all in any method or property." What's the point of making a generic type in T where you never use T?