问题描述
我刚刚用C#编写了此代码,以尝试了解当向下/向上转换一个类的实例时发生了什么.
I've just coded this in C# to try and understand what's happening when you downcast/upcast an instance of a class.
Class1.cs
Class1.cs
using System;
public class Shapes
{
protected int _x;
protected int _y;
public Shapes()
{
_x = 0;
_y = 0;
}
public virtual void Printing()
{
Console.WriteLine("In Shapes");
}
}
public class Circle: Shapes
{
public override void Printing()
{
Console.WriteLine("In Circle");
}
}
public class Square : Shapes
{
public new void Printing()
{
Console.WriteLine("In Square");
}
}
------------------------------------------------------------------------------------------
现在进入Program.cs
And now to Program.cs
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Shapes test1 = new Shapes();
Circle test2 = (new Circle());
Square test3 = new Square();
test1.Printing(); //In Shapes
test2.Printing(); //In Circle
test3.Printing(); //In Square
Console.WriteLine("------");
Shapes test4 = test2;
Shapes test5 = test3;
test4.Printing(); //In Circle (?)
test5.Printing(); //In Shapes (Ok)
Console.WriteLine("------");
Circle test6 = (Circle)test4;
Square test7 = (Square)test5;
test6.Printing(); //In Circle
test7.Printing(); //In Square
Console.WriteLine("------");
Square test10 = (Square)test4; //System.InvalidCastException: 'Unable to cast object of type 'Circle' to type 'Square'.'
Console.ReadLine();
}
}
}
所以问题是:
-
有人可以解释我先上传再下行的情况吗?
Can someone explain what's happening when I upcast then downcast?
为什么当我将test4放回到基类中时,test4为何打印圆圈"?
Why does test4 print "In circles" when I've made it into back into a base class?
将test4制成Shape后,为什么不能将其退回到Square(test10)?
After test4 has been made into a Shape, why can't it go back down into Square (test10)?
推荐答案
1/3)当您向下转换/向上转换对象时,实际上并没有更改类型,而只是可以访问该更改的方法和字段.这就是为什么如果Shape
开始时是Circle
,则不能从Shape
转到Square
的原因. Circle
和Square
都是Shapes
是,但是Circle
不是Square
.
1/3) When you downcast/upcast the object doesn't actually change type, it's just the methods and fields that you have access to that change. That's why you can't go from a Shape
to a Square
if the Shape
was a Circle
at the start. The Circle
and the Square
are both Shapes
yes, but a Circle
is not a Square
.
2)由于对象在投射时不会改变类型,因此test4
仍然是Circle
.只是您不再知道".实际上,如果通过调用test4.GetType()
打印它的类型,则会得到Circle
2) Since the object does not change type when you cast it, test4
is still a Circle
. It's just that you "don't know it anymore". In fact if you print it's type by calling test4.GetType()
you would get Circle
这篇关于上流和下流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!