Covariant in C #

Source: Internet
Author: User
Covariant can be understood as a variant, that is, converting one type to another.
Anders mentioned the variation of arrays in the array chapter of <the C # promgramiming language>.
If a reference type A can be implicitly or explicitly converted to B, A [R] can also be converted to B [R]. R can be specified arbitrarily, but a and B must be the same, this relationship is called array variation. array variations cannot be extended to value types. For example, they cannot be converted from int [] to object [] or from byte [] to int [].
Today, I found a post on Bill Wanger's blog about the variation of the function return type. C # does not support the variation of the function return type, for example, the following Code It cannot pass the mutation Class Classparent
{
Static   Void Main ()
{

}
Protected   Virtual Classparent getthing ()
{
Return Null;
}

}

Class Classson: classparent
{
Protected   Override Classson getthing ()
{
Return Null;
}
}

An error is reported during compilation. If the method is overloaded, the return type cannot be changed, which is supported in C ++.
Bill Wanger said that it can be implemented using a model interface. My C # is 1.1 and does not support the model, but it also sticks the code below Public   Interface Producer < T >
{
T getthing ();
}

Public   Class D: Producer < D >
{< br> Public D getthing ()
{< br> return null ;
}
}

in this way, if the value of T is appropriately limited, the variant of the return type of the C ++ function can be implemented using the model.

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.