简体   繁体   中英

Casting object of inherited class to instance of inheriting type

I have the following code.

class Program
{
    static void Main(string[] args)
    {
        Outer outer = new Outer();
        Inner inner = new Inner();

        Outer outer2 = new Inner();
        Inner inner2 = new Outer();
    }
}
public class Outer { }
public class Inner : Outer { }

I get the compiler error when assigning new Outer() to inner2 because it's of type Inner . I understand that it's to do with the inheritance but I can not figure out why because the contents are the same. Also, how can I force it to be cast to Inner .

I have tried

(inner)new Outer();
new Outer() as Inner;

But it threw an exception about conversion in the former and became null in the latter. Not sure what to google for to find out. I mean like this but the exact opposite.

A subclass is of type base class, but not the opposite. consider renaming them to

class Dog {}
class GermanShepard : Dog {}

This makes it clear that A German Sheppard is definitely a dog. But a dog is not necessarily a German Shepard.

writing the following is not possible, since the new dog could end up being another type of dog.

GermanShepard fred = new Dog();  //error!!

It might be a Shitzu or a Labrador. But you can always cast a German Shepard to a dog. Similarly you can always cast a Labrador to a dog.

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