[英]Why does this generic method call the base class method, not the derived class method?
[英]Derived class does not call base class method
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();
}
}
OUTPUT:
This is the derived class.
This is the derived class.
我不明白为什么第二次调用打印派生类的print()方法,因为我将mybc对象转换为基类。 我希望它能打印基类打印方法。 我在这里错过了什么吗?
变量类型和实例类型是两种不同的类型。 转换不会更改实例类型。
当您声明一个方法是虚拟/抽象时,您说您希望实例类型在被调用时确定行为。
另请注意,此赋值有效 - 不需要使用强制转换语法将变量类型从子类更改为baseclass。 这种演员表可以隐含地完成。
MyBaseClass mybc = derived;
你已经覆盖了它。 它只调用派生方法。 您必须显式调用基类的方法 :
override public void Print() {
base.Print();
Console.WriteLine("This is the derived class.");
}
覆盖虚方法的重点是调用对象的底层(运行时)类型的版本,而不是静态(编译时)类型的版本 - 即使通过声明为基类的类型调用它也是如此类。
所以这完全符合它的行为。
如果不是这种情况,则会使类层次结构的很多实用程序变得无用,因为您无法通过将类传递给自定义的派生类来更改传递给方法的类类型的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.