简体   繁体   中英

Why does the cast to the baseclass work by the keyword new?

Regarding this this post , it seem not to be possible to cast an derived class to it´s base class by the keyword as .

In the code of that post is used the keyword override . But when I use instead the keyword new , then the cast to the base-class becomes visible:

// base class
public class Aircraft
{
    public virtual void fly()
    {
        Console.WriteLine("Aircraft flies");
    }
}

// derived class
public class Plane : Aircraft
{
    public new void fly()
    {
        Console.WriteLine("Plane flies");
    }
}

public class Program
{
    public static void Main()
    {
        var plane = new Plane();
        Console.WriteLine(plane.GetType()); // "Plane"
        plane.fly(); // "Plane flies"
    
        var aircraft = plane as Aircraft; // <-- cast to base class
        Console.WriteLine(aircraft.GetType()); // "Plane"
        aircraft.fly(); // "Aircraft flies"
    }
}

The code aircraft.GetType(); indicates that the cast to the base class didn´t happen. It´s still a Plane . But aircraft.fly(); says, that the cast to the base class worked, because the method says: "Aircraft flies".

Who can solve my confusion?

You have an object created here:

new Plane();

It will always be of type Plane and this type cannot be changed (it would be another object then). Cast does not "change type" of object.

Now you have two variables pointing to this object. First variable plane is of type Plane , and second variable aircraft is of type Aircfart .

Then, Plane class has two separate methods with the same signature - fly() . One is inherited from base Aircraft class and another is declared with new keyword. When you call plane.fly() - compiler has to choose from two methods and is chooses the one with new keyword (by design). When you call aircraft.fly() - compiler has only one method to consider - fly() defined in Aircraft .

If you would override fly method in Plane class instead of declaring a new method with the same signature - then only one fly() method would exist and called in both cases, with implementation of the Plane class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM