【发布时间】: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