在多态性中,只有派生类可以是基类,这里会发生什么?
在多态性中,我了解到只有派生类才能成为基类,但是看看我的示例,基类现在是派生类:
static void Main()
{
Person a = new Customer();
//here a base class is a derived class
Customer c = (Customer)a;
}
class Person
{
}
class Customer : Person
{
}
为什么这是可能的?
在基类上实例化时,派生类的成员不应该被丢弃吗?
如果我在基类中实例化派生类,分配的内存大小就是派生类的大小?
In Polymorphism I learned that only derived class can be the base class, but look at my example, a base class is now a derived class:
static void Main()
{
Person a = new Customer();
//here a base class is a derived class
Customer c = (Customer)a;
}
class Person
{
}
class Customer : Person
{
}
Why this is possible?
The members of the derived class should not be discarded when instantiated on a base class?
If I instantiate a derived class in a base class, the allocated memory size is the size of the derived class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于 a 实际上是一个 Client 对象,所以这可以正常工作。让我更具体地说:
a 是 Person 类型的“变量”,它可以保存从 Person 到其任何子类的任何类型的“对象”。
c 是 Client 类型的“变量”,可以保存从 Client 到其任何子类的任何类型的“对象”。
您所做的是将 Client 的“对象”放入 Person 的“变量”中。无论您将此对象移动到何处,它始终是一个 Client 对象。所以,我们需要记住的是,即使你把一个Client的“对象”放入Person类型的“变量”中,这个对象类型仍然是client。在下一条语句中,您刚刚将对象移动到正确的类型。
变量就像一个篮子。它可以容纳任何比它小的东西。如果你把这个物体从篮子里拿出来,放到另一个篮子里,这个物体还是一样。
Since a is actually a Client object this would work fine. Let me be more specific:
a is a "variable" of type Person, it can hold an "object" of any type from Person to any of its child classes.
c is a "variable" of type Client and can hold an "object" of any type from Client to any of its child classes.
What you've done is put an "object" of Client into "variable" of Person. Wherever you move this object, it'll always be a Client object. So, what we need to keep in mind is that even though you put an "object" of Client into a "variable" of Person type, the object type is still client. In the next statement you just moved the object into its correct type.
A variable is just like a basket. It can hold anything which is smaller than it. If you take out the object out of the basket and put it into another basket, the object still remains the same.
虽然上面的方法确实有效(如其他答案中所述),但以下方法会失败,这可能是不尝试将基类强制转换为派生类的要点(除非您在运行时真正知道类型)。
While the above does work (as noted in other answers), the following would fail, which is probably the point of not trying to cast a base class to a derived class (unless you really know the type at runtime).