向上倾斜和向下倾斜

时间:2017-08-31 23:03:02

标签: c# oop polymorphism

我只是用C#对此进行了编码,试图了解当您向下倾斜/向上翻译某个类的实例时发生了什么。

的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

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. 有人可以解释当我向上倾斜然后向下倾斜时发生了什么吗?

  2. 为什么test4打印"在圆圈"当我把它重新变成基类时?

  3. 将test4制作成Shape后,为什么它不能再回到Square(test10)?

1 个答案:

答案 0 :(得分:3)

1/3)当您向下/向上转换对象并未实际更改类型时,它只是您可以访问该更改的方法和字段。这就是为什么如果Shape在开始时SquareShape,您就无法从Circle转到CircleSquareShapes都是Circle是,但Square不是test4

2)由于对象在投射时没有改变类型,Circle仍然是test4.GetType()。只是你不再了解它了#34;。事实上,如果您通过拨打Circle来打印它,您会得到this.props.function1(); this.props.functions2();