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.
这篇关于多态性和铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多态性和铸造


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01