简体   繁体   中英

Cast to base class from derived class

My code:

class MyBaseClass 
{ 
    public void Print() 
    { 
        Console.WriteLine("This is the base class."); 
    } 
} 

class MyDerivedClass : MyBaseClass 
{ 
    new public void Print() 
    { 
        Console.WriteLine("This is the derived class."); 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
        MyDerivedClass derived = new MyDerivedClass(); 
        MyBaseClass mybc = (MyBaseClass)derived; 

        derived.Print(); // Call Print from derived portion. 
        mybc.Print(); // Call Print from base portion. 
    } 
} 

If I change the line: MyBaseClass mybc = (MyBaseClass)derived; to MyBaseClass mybc = new MyBaseClass(); , the result was the same to.

My question: Can you tell me what is the difference?

Thanks!

Well, your first code was a cast. Meaning any attributes you inherited would still be in your object mybc after that cast.

While

MyBaseClass mybc = new MyBaseClass();

is simply creating a completetely new instance of your base class. Since you hard coded your print method, it cannot change any output, since they're both of the same type.

If you would print an attribute of your class, like a name and a number, you would see the difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM