6

I have a method in my baseclass that returns a bool and I want that bool to determine what happens to the same overridden method in my derived class.

Base:

    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;
    }

Derived

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

    }

Note that bal comes from a constructor I made earlier

4

4 回答 4

10

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

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

}

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

于 2013-04-30T16:57:24.233 回答
2
if(base.Debt(bal)){
    // do A
}else{
    // do B
}

base指基类。所以在基类base.X中指代。X

于 2013-04-30T16:57:35.460 回答
2

调用base方法:

public override void Debt(double bal)
{
    var worked = base.Debt(bal);
    //Do your stuff
}
于 2013-04-30T16:57:39.980 回答
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
        }
    }
}

下面是 msdn 对虚拟方法的看法

于 2013-04-30T17:06:10.177 回答