上流和下流 [英] Upcasting and Downcasting

查看:93
本文介绍了上流和下流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚用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();
        }
    }
}

所以问题是:

  1. 有人可以解释我先上传再下行的情况吗?

  1. 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的原因. CircleSquare都是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

这篇关于上流和下流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆