Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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");
 }
}
------------------------------------------------------------------------------------------

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

So the questions are:

  1. Can someone explain what's happening when I upcast then downcast?

  2. Why does test4 print "In circles" when I've made it into back into a base class?

  3. After test4 has been made into a Shape, why can't it go back down into Square (test10)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

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) 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...