Inversion and interpretation covariant
And an inverter for parameter types are covariant template class / interface for the.
Suppose a parent Father
, a child class Child
, a class templateSampleTemplate<T>
simply put
- Covariance (covariant): require
SampleTemplate<Father>
local, can passSampleTemplate<Child>
. Common covariant type:IEnumberable
- Inverter: the need for
SampleTemplate<Child>
places that may be passedSampleTemplate<Father>
. Common Inverter type:List<Child>.Sort
function usedIComparer
understanding
Object-oriented programming, it is easy to understand, you need to place the parent class, you can use subclasses.
Conversely needs subclass place, but can not use the parent class.
So covariant it seems a matter of course, but looks a bit counter-inverter logic.
Here first look at how to define a template class supports the inverter or covariance.
- Covariance:
SampleTemplate<out T>
- Inverter:
SampleTemplate<in T>
Here in
and out
What does it mean?
Binding foregoing IEnumerable<out T>
and IComparer<in T>
:
- Covariance: In
IEnumberable
the, if needed a functionIEnumberable<Father>
as the reference, we passIEnumerbale<Child>
can, because we use thisIEnumerable
time, which is obtained from the elements, as theFather
process, so theIEnumerable
data is a出
direction correspondingout
. So incomingChild
class outputFather
class is no problem. - Inverter: when the
List<Child>
class Sort callIComparer
time, Sort function signature requirementsIComparer<Child>
, it will show the actualIComparer
pass aChild
, and this type will be the typeIComparer
used inside, thus corresponding toin
the direction. Template class natural long as the actual implementation, to acceptChild
the type can, in fact, is equivalent to a conversion subclass the parent class.
Therefore, the inverter and covariant corresponding are subclasses (subclasses can not convert to the parent) conversion to the parent class, except that a template class covariance subclass may receive an output parameter parent; and inverse change is the template class itself as an entity to be input from the external input sub-class, the class template to use him as a parent.