开发者

Does covariance/contravariance apply to implicitly convertable types that don't implement a common interface?

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开发者_JS百科 correct to talk about covariance/contravariance when dealing with conversion of generics of these types? Or is this a different concept?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜