C#:是方差(协方差/逆变)为多态性另一个词? [英] C# : Is Variance (Covariance / Contravariance) another word for Polymorphism?

查看:124
本文介绍了C#:是方差(协方差/逆变)为多态性另一个词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图协方差逆变从几个网上的文章和问题弄清楚的话的确切含义在计算器上,从我能理解,这只是作为多态性另一个词

难道我上面的说法正确吗?还是我听错了?


解决方案

这当然涉及到多态。我不会说他们只是一个字多态,但 - 他们的很具体的情况,在那里你可以把一种类型,好像它是在一定的语境中另一种类型的 的<。 / p>

例如,对于正常的多态,你可以把一个任何引用香蕉作为对水果参照 - 但是,这并不意味着你可以替换水果每个的时候,你看到的类型香蕉 。例如,列表&LT;香蕉&GT; 不能被视为列表&LT;水果GT; ,因为 list.Add(新的苹果())有效期为列表&LT;水果GT; 而不是列表&LT;香蕉&GT ;

协方差允许更大(不具体)型的API中被取代,其中原先类型是<青霉>仅在输出的位置(例如,作为返回值)使用的。逆变允许的小(更具体的)类型的API,其中的原始类型是要被替换的只有的在输入的位置使用。

这是很难进入的一个SO后的所有细节(虽然希望别人会做的比这更好的工作!)。埃里克利珀具有优良的系列博客文章的了。

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.

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>.

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.

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#:是方差(协方差/逆变)为多态性另一个词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆