157 recommendations for writing high-quality code to improve C # programs--recommendation 45: Specifying contravariance for generic type parameters

Source: Internet
Author: User

Recommendation 45: Specifying contravariance for generic type parameters

Contravariance refers to a method's parameters can be a base class for a delegate or a generic interface's parameter type. Common delegates that support contravariance in FCL4.0 are:

Func<int T,out tresult>

Predicate<in t>

Common delegates are:

Icomparer<in t>

The following example shows the benefits of specifying the inverse of a generic type parameter:

    classProgram {Static voidMain () {Programmer P=NewProgrammer {Name ="Mike" }; Manager m=NewManager {Name ="Steve" };        Test (P, m); }        Static voidTest<t> (imycomparable<t>T1, T T2) {            //omitted        }    }     Public Interfaceimycomparable<inchT>    {        intCompare (T other); }     Public classEmployee:imycomparable<employee>    {         Public stringName {Get;Set; }  Public intCompare (Employee other) {returnName.compareto (Other.        Name); }    }     Public classProgrammer:employee, imycomparable<programmer>    {         Public intCompare (Programmer other) {returnName.compareto (Other.        Name); }    }     Public classManager:employee {}

In the above example, if the IN keyword is not specified for the generic parameter T of the interface imycomparable, a test (P,M) compilation error will result. Because of the introduction of the inverse of the interface, this allows the method test to support more scenarios. This should always be noted in the actual encoding of the version after FCL4.0.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--recommendation 45: Specifying contravariance for generic type parameters

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.