简体   繁体   English

派生类不调用基类方法

[英]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: OUTPUT:

This is the derived class.
This is the derived class.

I do not understand why second call prints derived class's print() method because I cast mybc object to base class. 我不明白为什么第二次调用打印派生类的print()方法,因为我将mybc对象转换为基类。 I expect it to print base class print method instead. 我希望它能打印基类打印方法。 Am I missing something here? 我在这里错过了什么吗?

The variable type and the instance type are two different types. 变量类型和实例类型是两种不同的类型。 Casting does not change the instance type. 转换不会更改实例类型。

When you declare a method to be virtual/abstract, you're saying that you want the instance type to determine behavior when called. 当您声明一个方法是虚拟/抽象时,您说您希望实例类型在被调用时确定行为。

Also note that this assignment is valid - cast syntax is not needed to change variable type from subclass to baseclass. 另请注意,此赋值有效 - 不需要使用强制转换语法将变量类型从子类更改为baseclass。 This kind of cast can be done implicitly. 这种演员表可以隐含地完成。

MyBaseClass mybc = derived;

You have overridden it. 你已经覆盖了它。 It only calls the derived method. 它只调用派生方法。 You have to explicitly call the base class' method : 您必须显式调用基类的方法

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

The whole point of overriding virtual methods is that the version for the underlying (runtime) type of the object is called, rather than the one for the static (compile-time) type - even when you call it through a type declared as the base class. 覆盖虚方法的重点是调用对象的底层(运行时)类型的版本,而不是静态(编译时)类型的版本 - 即使通过声明为基类的类型调用它也是如此类。

So this is behaving exactly as it should. 所以这完全符合它的行为。

If this was not the case, it would make a lot of the utility of a class hierarchy useless, because you couldn't change the behaviour of a class type passed to a method by passing it a customised derived class. 如果不是这种情况,则会使类层次结构的很多实用程序变得无用,因为您无法通过将类传递给自定义的派生类来更改传递给方法的类类型的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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