在基类和子类之间转换 [英] casting between base class and child classes

查看:423
本文介绍了在基类和子类之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于在基类和其子类之间进行转换的问题:

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

(1)为什么允许?

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

(2)为什么不允许? / p>

(2) Why is this not allowed?

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

(3)为什么允许?

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

(4)为什么允许?

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


推荐答案

强制转换的原因是允许还是不允许基本背后的继承。

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.

对于你的例子(2):

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

这是不可能的,因为你要为Dog指定一个Animal对象,但你知道并不是所有的动物是狗,有些动物是猫。

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.

例如(3)& (4):

And for examples (3) & (4):

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

这与上面的示例1相同。所有的狗都是动物,所以任何狗都可以归类为动物和演员(事实上你不需要演员,将有一个隐式的演员,你可以写它 Animal b = 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;

这篇关于在基类和子类之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆