使用baseclass方法返回值?

The*_*Ace 6 c# methods inheritance

我在我的基类中有一个方法返回一个bool,我想要那个bool来确定在我的派生类中相同的重写方法会发生什么.

基础:

    public bool Debt(double bal)
    {
        double deb = 0;
        bool worked;

        if (deb > bal)
        {
            Console.WriteLine("Debit amount exceeds the account balance – withdraw cancelled");
            worked = false;
        }
        else

        bal = bal - deb;
        worked = true;

        return worked;
    }
Run Code Online (Sandbox Code Playgroud)

派生

public override void Debt(double bal)
    {
        // if worked is true do something

    }
Run Code Online (Sandbox Code Playgroud)

请注意,bal来自我之前制作的构造函数

PHe*_*erg 10

您可以使用base关键字调用基类方法:

public override void Debt(double bal)
{
    if(base.Debt(bal))
        DoSomething();

}
Run Code Online (Sandbox Code Playgroud)

如上面的注释所示,您需要确保在基类中存在具有相同签名(返回类型和参数)的虚方法,或者从派生类中删除override关键字.