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()");
}
}
我知道,为了将 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.
这篇关于多态性和铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多态性和铸造
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
