简体   繁体   中英

Check if the instance is type of base class or derived class after keyword 'as'?

Please look at the following code:

// Base class
public abstract class Aircraft
{
    public virtual void Fly()
    {
        Console.WriteLine("Aircraft flies");
    }
}

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

// Execution
public class Program
{
    public static void Main()
    {
        var lPlane = new Plane();
        Console.WriteLine(lPlane.GetType()); // Plane
        lPlane.Fly(); // Plane flies

        var lAircraft = lPlane as Aircraft;
        Console.WriteLine(lAircraft.GetType()); // Plane
        lAircraft.Fly(); // Aircraft flies
    }
}

The following line casts the Plane to an Aircaft :

var lAircraft = lPlane as Aircraft;

So I would expected, that lAircraft is type of Aircraft now. But it isn´t. It is of type Plane :

Console.WriteLine(lAircraft.GetType()); // Plane

How can I check if the current instance is type of base class or derived class after cast by the keyword as ?

This code:

var lAircraft = lPlane as Aircraft;

Will be compiled to this:

Aircraft aircraft = lPlane;

So that means the as keyword here do nothing because you can't convert your derived class to it's base class. To find out more you can read this answer: https://stackoverflow.com/a/8329517/2946329

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