Covariant out and Contravariance in C #

Source: Internet
Author: User

Variability is often used in generic interfaces and generic delegates

In Contravariance, out covariant

From list<string> to list<object> called covariant (string derives from object, it is reasonable to turn a string into object, it is reasonable for subclasses to replace the parent class)

It is unreasonable to go from list<object> to List<string>, which is called inversion (by turning the object into a string and turning the parent class into a subclass, which is called inversion).

1. Invert Code Masking

  Static voidMain (string[] args) {Icovariant<Object> iobj =NewSample<object>(); Icovariant<String> ISTR =NewSample<string>(); //You can assign ISTR to Iobj because//The Icovariant interface is covariant. //iobj = ISTR;ISTR =iobj;//Convert from Object type to string type, parent class to subclass is Contravariant console.readline (); }        //covariant interface.        Interfaceicovariant<inchR> { }        //extending covariant interface.        Interfaceiextcovariant<inchR>: icovariant<r> { }        //implementing covariant interface.        classSample<r>: icovariant<r> {}

2. Co-change Demo

   Static voidMain (string[] args) {Icovariant<Object> iobj =NewSample<object>(); Icovariant<String> ISTR =NewSample<string>(); //You can assign ISTR to Iobj because//The Icovariant interface is covariant. //iobj = ISTR;Iobj =ISTR;            //From string to type Object, sub-type to parent (the Richter substitution principle) is covariant        Console.ReadLine (); }        //covariant interface.        Interfaceicovariant< outR> { }        //extending covariant interface.        Interfaceiextcovariant< outR>: icovariant<r> { }        //implementing covariant interface.        classSample<r>: icovariant<r> {}

Covariant out and Contravariance in C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.