Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c# - casting between base class and child classes

I have a question about casting between a base class and its child classes:

(1) Why is this allowed?

BaseClass b = new ChildClassA();
ChildClassA c = (ChildClassA)b

(2) Why is this not allowed?

ChildClassA c = (ChildClassA)new BaseClass();
BaseClass b = (BaseClass)c;

(3) Why is this allowed?

BaseClass b = new BaseClass();
ChildClassA c = (ChildClassA)c;

(4) Why is this allowed?

ChildClassA c = new ChildClassA();
BaseClass b = (BaseClass)c;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reasons the cast is either allowed or not allowed is the basics behind inheritance.

A child class (or a derived class) is always a base class, but the opposite is not true.

To explain, let's use some more real world names for your example classes:

class Animal
{
}

class Dog : Animal
{
}

class Cat : Animal
{
}

So for your example (1):

Animal b = new Dog();
Dog c = (Dog)b

This is true because all Dogs are Animals and your Animal b is actually a dog so the cast is successful.

For your example (2):

Dog c = (Dog)new Animal();
Animal b = (Animal)c;

This is impossible because you are assigning an Animal object to a Dog, but you know that not all animals are Dogs, some animals are cats.

And for examples (3) & (4):

Dog c = new Dog();
Animal b = (Animal)c;

This is the same as your example 1 above. All dogs are animals, so any dog can be classified as an animal and cast (in fact you don't need the cast, there would be an implicit cast and you can write it as Animal b = c;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...