C # covariant and invert,

Source: Internet
Author: User

C # covariant and invert,

We know that in C #, the instance of the derived class can be assigned to the Base Class Object.

There is no problem. Next we will make some changes.

Covariant

Isn't the Dog class inherited from the Animal class? Why can't it be used here?

In this Code, the dogMarker and animalMarker variables are of the Factory <Dog> and Factory <Animal> types, that is, they are at the same level. Therefore, when dogMarker is assigned to animalMarker, the compiler reports an error. So if we want the above Code to run normally, what should we do?

Remember that when learning a parameter, there is a keyword -- out; if the type parameter is only used as the output value, it applies to any generic delegation.

The relationships between these structured delegated effects are called covariant.

Inverter

Let's take a look at a piece of code.

As you know this time, the error message must be of different types and cannot be assigned a value. Let's take a closer look at the exception prompt. How can we achieve "inverter? In fact, you only need a simple keyword (in) to solve the problem.

This kind of feature allows the object of the derived class to be passed in when the base class is expected to be passed in is inverter.

Summary

Only the reference type is applicable to the covariant and inverter, because the value type cannot derive a new type.

Explicit changes use the in and out keywords only for delegation and interfaces, and classes, structures, and methods are not applicable.

Related Article

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.