简体   繁体   中英

Contravariance generic modifier in

 public interface IOInitializable<in ItemType>

What does contravariant: converting from narrower (circle) to wider (Shapes)

mean for an interface?

What are the consequence and the dangers?

I've read http://msdn.microsoft.com/en-us/library/dd469484.aspx but this does not help me.

I'd recommend reading this explaination from Tomas:

The theory behind covariance and contravariance in C# 4

It boils down to the fact that if you have a method call that is passing a number of "Circles", you can use a function that accepts a number of "Shapes" as long as it doesn't return a "Shape" (because that may or may not be a "Circle").

IComparer is a good example to demonstrate this. IComparer looks like this:

IComparer<in T>

Take the following:

IComparer<Primate>
IComparer<Chimpanzee>

where Chimpanzee : Primate (of course). A method which requires an IComparer<Chimpanzee> can take an IComparer<Primate> as an argument, because if the comparer can compare primates, it can also compare chimpanzees, as it uses traits common to the two types to affect the comparison .

A good way to think of this is in terms of functionality. Covariance allows more complex objects to be passed which implement a core functionality (like passing a string for an object). Contravariance does something similar... comparing all primates is more complex than just comparing chimpanzees. It allows you to replace a comparer for a specific type with one which compares a more general type. In this sense, the "in" applies more to the functionality of the method than the actual type passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM