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.
这篇关于多态性和铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多态性和铸造
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01