问题描述
我想了解 c# 中的多态性,因此通过尝试几种构造,我想出了以下案例:
I want to understand polymorphism in c# so by trying out several constructs I came up with the following case:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw()");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Circle.Draw()");
}
}
我知道,为了将 Draw() 消息发送到几个相关对象,以便它们可以根据自己的实现采取行动,我必须更改(在这种情况下)形状指向"的实例:
I understand that in order to send the Draw() message to several related objects, so they can act according to its own implementation I must change the instance to which (in this case) shape is 'pointing' to:
Shape shape = new Circle();
shape.Draw(); //OK; This prints: Circle.Draw()
但是为什么,当我这样做时:
But why, when I do this:
Circle circle = new Circle();
circle.Draw(); //OK; This prints: Circle.Draw()
Shape shape = circle as Shape; // or Shape shape = (Shape)circle;
shape.Draw();
它打印:Circle.Draw()"
It prints: "Circle.Draw()"
为什么它在演员表之后调用 Circle.Draw() 而不是 Shape.Draw()?这是什么原因?
Why it calls the Circle.Draw() instead Shape.Draw() after the cast? What is the reasoning for this?
推荐答案
强制转换不会改变对象的运行时类型以及每个实例具有的特定虚拟方法的实现.
Casting does not change run-time type of object and what implementation of particular virtual method each instance have.
请注意,您作为样本的以下 2 个案例是相同的:
Note that following 2 cases you have as sample are identical:
Shape shape = new Circle();
shape.Draw(); //OK; This prints: Circle.Draw()
和:
Circle circle = new Circle();
Shape shape = circle as Shape;
shape.Draw();
第一个基本上是第二个的较短版本.
The first one is essentially shorter version of the second.
这篇关于多态性和铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!