【发布时间】:2016-01-01 20:31:17
【问题描述】:
class MyBaseClass
{
virtual public void Print()
{
Console.WriteLine("This is the base class.");
}
}
class MyDerivedClass : MyBaseClass
{
override 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();
mybc.Print();
}
}
输出:
This is the derived class.
This is the derived class.
我不明白为什么第二次调用会打印派生类的 print() 方法,因为我将 mybc 对象转换为基类。我希望它改为打印基类打印方法。我在这里遗漏了什么吗?
【问题讨论】:
-
查看此网站上的类似问题以进行深思熟虑的讨论:stackoverflow.com/questions/1334254/…
-
删除 override 关键字,一切正常
-
@PranavPatel 从技术上讲它可以工作,但通常这是一个糟糕的设计。
标签: c# inheritance derived-class base-class