虚方法和覆写方法
请大家帮一下忙~~~~~代码:
class MyBaseClass
{
virtual public void Print()
{
Console.WriteLine("this is the base class");
}
}
class MyDerivedClass : MyBaseClass
{
public override void Print()
{
Console.WriteLine("this is the derived class");
base.Print();
}
}
class Program
{
static void Main(string[] args)
{
MyDerivedClass derived = new MyDerivedClass();
MyBaseClass myb = (MyBaseClass)derived; //强制转换成基类
//MyBaseClass myb = new MyBaseClass();
//MyDerivedClass derived = (MyDerivedClass)myb;
derived .Print();
myb.Print();
Console.ReadLine();
}
}
问题:
一、MyBaseClass myb = (MyBaseClass)derived; 注释说的是 强制转换成基类 但是 MyBaseClass本来就是基类啊!那我明白啦,到底是给谁强制转换啊?
二、//MyBaseClass myb = new MyBaseClass(); //MyDerivedClass derived = (MyDerivedClass)myb;这个输出提示无法强制转换类型的错误,为什么我基类和派生类调转过来强制转换类型会提示错误呢??
请帮帮忙啊~~~谢谢~~~~~~~