【问题标题】:Using a baseclass method return value?使用基类方法返回值?
【发布时间】:2013-04-24 16:23:32
【问题描述】:

我的基类中有一个返回 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;
    }

派生

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

    }

注意 bal 来自我之前创建的构造函数

【问题讨论】:

  • 确保您的基类方法是虚拟的:public virtual bool Deb(double bal) 否则您的派生类将隐藏它。只是一个旁注。
  • 同样返回值类型必须匹配,否则会出现编译错误'<namespace>.Derived.Debt(double)': return type must be 'bool' to match overridden member '<namespace>.Base.Debt(double)'

标签: c# inheritance methods


【解决方案1】:

正如其他几个人提到的,您可以使用base.Debt(bal) 调用您的基类方法。我还注意到您的基类方法未声明为虚拟。默认情况下,C# 方法不是虚拟的,因此您不会在派生类中重写它,除非您在基类中将其指定为虚拟。

//Base Class
class Foo
{
    public virtual bool DoSomething()
    {
        return true;
    }
}

// Derived Class
class Bar : Foo
{
    public override bool DoSomething()
    {
        if (base.DoSomething())
        {
           // base.DoSomething() returned true
        }
        else
        {
           // base.DoSomething() returned false
        }
    }
}

Here'smsdn 对虚拟方法的看法

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 最好将if 之后的区域括起来并在那里做你的事情,而不是调用另一个方法来做。为什么要让你的调用堆栈比它必须的更深?
    • @Jeff - 我把方法调用放在那里纯粹是为了表明那里应该发生一些事情。也可以是内联语句。
    • 我明白你在说什么,只是无法判断结果是真是假
    • @TheAce:在if 语句中。 if 评估基类方法的返回值。如果你落入if检查,那是真的。否则,它是错误的。
    【解决方案3】:

    调用base方法:

    public override void Debt(double bal)
    {
        var worked = base.Debt(bal);
        //Do your stuff
    }
    

    【讨论】:

      【解决方案4】:
      if(base.Debt(bal)){
          // do A
      }else{
          // do B
      }
      

      base 指的是基类。所以base.X 指的是基类中的X

      【讨论】:

        猜你喜欢
        • 2021-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-12
        • 1970-01-01
        相关资源
        最近更新 更多