覆盖基类中的函数

Gar*_*thD -2 c# oop inheritance overriding

在下面的示例中,我想替换部分计算,而不必在派生子类中重新实现整个计算.

class DummyCalcBase
{
    public int changeable_part()
    {
        return 5;
    }

    public int common_calculation()
    {
        return 5 * changeable_part();
    }
}

class DummyCalc : DummyCalcBase
{
    public new int changeable_part()
    {
        return 10;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int c = new DummyCalcBase().common_calculation();
        Console.WriteLine("Base gives " + c.ToString());

        int c2 = new DummyCalc().common_calculation();
        Console.WriteLine("Calc gives " + c2.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后给出输出:Base给出25 Calc给出25

我想要的是让DummyCalc().common_calculation()调用新的changeable_part(并给出答案50).

这意味着我不必将相同的方法复制并粘贴到子类中.

ASh*_*ASh 7

override如果是的话,你可以使用方法virtual

class DummyCalcBase
{
    public virtual int changeable_part()
    {
        return 5;
    }

    public int common_calculation()
    {
        return 5 * changeable_part();
    }
}

class DummyCalc : DummyCalcBase
{
    public override int changeable_part()
    {
        return 10;
    }
}
Run Code Online (Sandbox Code Playgroud)

new关键字的方法只隐藏基类的方法

如果method是virtual,则以下代码将计算50:

DummyCalcBase dummy = new DummyCalc();
int calc = dummy.common_calculation();
Run Code Online (Sandbox Code Playgroud)

SO:新vs超越差异