如何从子类中的方法调用子类中覆盖的父方法?

h0a*_*0ax 1 c# oop methods method-call

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

基类

class LandVehicle : Vehicle
    {
        public override string Move()
        {
            return "Move on the wheels";
        }
    }
Run Code Online (Sandbox Code Playgroud)

子类

class FamilyCar : LandVehicle
{
        public override string Move()
        {
            return "Pip pip!";
        }
}
Run Code Online (Sandbox Code Playgroud)

Ama*_*n B 5

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

class LandVehicle : Vehicle
    {
        public override string Move()
        {
            return "Move on the wheels";
        }
    }
Run Code Online (Sandbox Code Playgroud)

子类

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


归档时间:

查看次数:

57 次

最近记录:

5 年,3 月 前