Understanding of the inverter in the c # and covariant

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 pass SampleTemplate<Child>. Common covariant type:IEnumberable
  • Inverter: the need for SampleTemplate<Child>places that may be passed SampleTemplate<Father>. Common Inverter type: List<Child>.Sortfunction 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 inand outWhat does it mean?

Binding foregoing IEnumerable<out T>and IComparer<in T>:

  • Covariance: In IEnumberablethe, if needed a function IEnumberable<Father>as the reference, we pass IEnumerbale<Child>can, because we use this IEnumerabletime, which is obtained from the elements, as the Fatherprocess, so the IEnumerabledata is a direction corresponding out. So incoming Childclass output Fatherclass is no problem.
  • Inverter: when the List<Child>class Sort call IComparertime, Sort function signature requirements IComparer<Child>, it will show the actual IComparerpass a Child, and this type will be the type IComparerused inside, thus corresponding to inthe direction. Template class natural long as the actual implementation, to accept Childthe 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.

Guess you like

Origin www.cnblogs.com/mosakashaka/p/12651662.html