【问题标题】:How to call the parent method that is overrided in a subclass from the method in the child class? [duplicate]如何从子类中的方法调用子类中被覆盖的父方法? [复制]
【发布时间】:2020-11-04 19:43:55
【问题描述】:

我想调用 FamilyCar 方法 Move()。如果 FamilyCar 是 LandVehicle,我想同时调用 LandVehicle Move() 方法。 我正在寻找非常基本的方法。

基类

class LandVehicle : Vehicle
    {
        public override string Move()
        {
            return "Move on the wheels";
        }
    }

子类

class FamilyCar : LandVehicle
{
        public override string Move()
        {
            return "Pip pip!";
        }
}

【问题讨论】:

  • “如果 FamilyCar 是陆地车辆……”您是什么意思? FamilyCar 始终是 LandVehicle。
  • 没错,事实上我有更多的子类,除了 FamilyCar。对于每个 LandVehicle,我希望 LandVehicle 中的方法 Move() 调用并额外调用他们自己的方法,该方法称为更详细的方法。
  • 你的意思是如何在派生类中调用基方法,如base.Move() in FamilyCar.Move()
  • 可以使用base.Move()调用父级的move函数。当然你不能return两次所以你必须重构那部分。
  • @h0ax 这是多态机制的一部分,在这里,根据您的要求调用基类:What is polymorphism。我希望这可以帮助您享受 C# 编码:How do I improve my knowledge in C#.

标签: c# oop methods method-call


【解决方案1】:

可以使用base.Move()调用父类的Move方法:

class LandVehicle : Vehicle
    {
        public override string Move()
        {
            return "Move on the wheels";
        }
    }

子类

class FamilyCar : LandVehicle
{
        public override string Move()
        {
            base.Move(); //this will call LandVehicle.Move()
            return "Pip pip!";
        }
}

【讨论】:

  • 将调用但对结果不执行任何操作...
  • @Selvin 没错,但我认为 OP 只是想知道如何调用基类方法
猜你喜欢
  • 2014-05-11
  • 2017-11-11
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
相关资源
最近更新 更多