问题描述
我试图从网上的几篇文章和 StackOverflow 上的问题中弄清楚 Covariance
和 Contravariance
这两个词的确切含义,据我所知,它只是多态性的另一种说法.
I am trying to figure out the exact meaning of the words Covariance
and Contravariance
from several articles online and questions on StackOverflow, and from what I can understand, it's only another word for polymorphism.
我对上述说法是否正确?还是我弄错了?
Am I correct with the above statement? Or have I got it wrong ?
推荐答案
肯定和多态有关.我不会说它们只是多态性的另一个词"——它们是关于非常具体的情况,在这种情况下,您可以将一种类型视为另一种类型在特定上下文中.
It's certainly related to polymorphism. I wouldn't say they're just "another word" for polymorphism though - they're about very specific situations, where you can treat one type as if it were another type in a certain context.
例如,对于正常的多态性,您可以将任何对 Banana
的引用视为对 Fruit
的引用 - 但这并不意味着您可以替换 Fruit
每次你看到类型Banana
.例如,不能将 List
视为 List
,因为 list.Add(new Apple())
对 List<Fruit>
有效,但对 List
For instance, with normal polymorphism you can treat any reference to a Banana
as a reference to a Fruit
- but that doesn't mean you can substitute Fruit
every time you see the type Banana
. For example, a List<Banana>
can't be treated as a List<Fruit>
because list.Add(new Apple())
is valid for List<Fruit>
but not for List<Banana>
.
协方差允许在 API 中替换更大"(不太具体)的类型,其中原始类型仅用于输出"位置(例如,作为返回值).逆变允许在 API 中替换更小"(更具体)的类型,其中原始类型仅用于输入"位置.
Covariance allows a "bigger" (less specific) type to be substituted in an API where the original type is only used in an "output" position (e.g. as a return value). Contravariance allows a "smaller" (more specific) type to be substituted in an API where the original type is only used in an "input" position.
很难在一篇 SO 帖子中介绍所有细节(尽管希望其他人会做得比这更好!).Eric Lippert 有一篇关于它的优秀系列博文.
It's hard to go into all the details in a single SO post (although hopefully someone else will do a better job than this!). Eric Lippert has an excellent series of blog posts about it.
这篇关于C#:方差(协方差/逆变)是多态性的另一个词吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!