C#:方差(协方差/逆变)是多态性的另一个词吗?

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

问题描述

我试图从网上的几篇文章和 StackOverflow 上的问题中弄清楚 CovarianceContravariance 这两个词的确切含义,据我所知,它只是多态性的另一种说法.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)