协变/逆变是否适用于未实现公共接口的隐式可转换类型?
我目前正在阅读 C# 中的协方差和逆变。
所有示例都具有可转换对象的详细信息,并且由于接口实现的准确性而有所不同,例如
,其中 Circle : IShape
协方差:SomeType
逆变:SomeType
如果 TypeA
和 TypeB
各自编写了一个隐式转换器
来转换为另一种类型,但是 不实现任何通用接口,在处理这些类型的泛型转换时谈论协变/逆变是否仍然正确?或者这是一个不同的概念?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不同的概念。
out
意义上的协方差(或通过in
实现的逆变)始终是引用保留的,根本不进行任何变换 - 只是在其他(可证明的)术语中具有相同的引用。这也是为什么它不适用于实现接口的结构,因为盒子不保留引用。相同的引用保留逻辑适用于引用类型数组的协变赋值。Different concept. Covariance in the
out
sense (or contravariance viain
) 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.这些类型不需要实现通用接口即可实现协变/逆变。
这些术语仅指转换是否会导致信息丢失或潜在的信息增加。这在应用于继承对象时与应用于双精度数和浮点数时同样相关。
所以,是的,只要存在隐式转换器,在谈论没有公共接口的对象时谈论协变/逆变仍然是正确的。
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.