简体   繁体   中英

Invalid cast exception on using virtual method with base class being the run time type c#

I know this is nothing new, I just want to know why this throws an InvalidCastException since the runtime type here (A which is the base class) has an implementation for that method, thanks.

class Program
{
    static void Main(string[] args)
    {
        B b = (B)new A();
        Console.WriteLine(b.Foo());
        Console.ReadLine();
    }
}

class A
{
    public virtual string Foo() => "Hello from base class";
}

class B : A
{
    public override string Foo() => "Hello from sub class";
}

Just because A is the base class of B doesn't change that A isn't B . It's B who's A .

For example, you're a mix of your dad and you mother, but you're not your dad or your mother. If the police gets you doing something wrong with your car, would the police ask for your dad's or mom's driving license?

You can compare the police with the compiler. The compiler won't accept that you set an instance of A in a reference typed as B , because they're different types.

What compiler can accept is that an instance of B upcasted to A could be set to a reference of A :

B b = new B();
A a = b;
b = (B)a;

You can't cast base class to derived. It's possible that B declares some new member (eg method M1 ) which are absent in A . And if it was possible to cast, if you call M1 method for A , it would be absent. So the runtime prevents such casting.

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