协变/逆变是否适用于未实现公共接口的隐式可转换类型?

发布于 2024-11-24 21:54:41 字数 433 浏览 3 评论 0原文

我目前正在阅读 C# 中的协方差和逆变。

所有示例都具有可转换对象的详细信息,并且由于接口实现的准确性而有所不同,例如

,其中 Circle : IShape

协方差:SomeType。作为 SomeType
逆变:SomeTypeas SomeType


如果 TypeATypeB 各自编写了一个隐式转换器来转换为另一种类型,但是 不实现任何通用接口,在处理这些类型的泛型转换时谈论协变/逆变是否仍然正确?或者这是一个不同的概念?

I'm currently reading up on Covariance and Contravariance in C#.

All examples have details of objects being convertable and differ because of the accuracy from the Interface implementation e.g.

Where Circle : IShape

Covariance: SomeType<Circle> as SomeType<IShape>
Contravariance: SomeType<IShape> as SomeType<Circle>


If TypeA and TypeB each have an implicit converter written to convert to the other type, but do not implement any common Interface, is it still correct to talk about covariance/contravariance when dealing with conversion of generics of these types? Or is this a different concept?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

过去的过去 2024-12-01 21:54:41

不同的概念。 out 意义上的协方差(或通过 in 实现的逆变)始终是引用保留的,根本不进行任何变换 - 只是在其他(可证明的)术语中具有相同的引用。这也是为什么它不适用于实现接口的结构,因为盒子不保留引用。相同的引用保留逻辑适用于引用类型数组的协变赋值。

Different concept. Covariance in the out sense (or contravariance via in) is always reference-preserving, with no transformation at all - just the same reference in other (provable) terms. This is also why it doesn't apply to structs that implement an interface, as a box is not reference-preserving. The same reference-preserving logic applies to covariant assignment of arrays of reference-types.

筱果果 2024-12-01 21:54:41

这些类型不需要实现通用接口即可实现协变/逆变。

这些术语仅指转换是否会导致信息丢失或潜在的信息增加。这在应用于继承对象时与应用于双精度数和浮点数时同样相关。

所以,是的,只要存在隐式转换器,在谈论没有公共接口的对象时谈论协变/逆变仍然是正确的。

The types do not need to implement a common interface in order to be co/contra-variant.

The terms simply refer to whether the conversion will result in the loss of information or the potential increase in information. This is just as relevant when applied to inherited objects as it is when applied to doubles and floats.

So yes, it is still correct to talk about co/contra-variance when talking about objects that have no common interface as long as there is an implicit converter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文