多态性与铸造 [英] Polymorphism and casting
问题描述
我想尝试一些结构来理解多态性在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()");
}
}
据我所知,为了送抽奖()消息给多个相关对象,因此它们可以根据它自己的执行行动我必须改变到的实例(本例中)的形状是定点,以
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.
需要注意的是以下两个情况下,你必须为样本是相同的:
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.
这篇关于多态性与铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!