【发布时间】:2021-10-18 18:06:20
【问题描述】:
下面是我为模拟银行账户的程序编写的代码 sn-p。
我想知道是否有更简洁的方法来设计friendlyName 字段的继承?
理想情况下,我会将其存储为 const,但它会阻止在子类中重新分配其值。
非常感谢!
public abstract class Account
{
protected string friendlyName;
public string ShowBalance()
{
var message = new StringBuilder();
message.Append($"Your {friendlyName} balance is {Balance}");
.Append("See you soon!");
return message.ToString();
}
}
public class SavingsAccount : Account
{
public SavingsAccount()
{
friendlyName = "savings account";
}
}
public class CurrentAccount : Account
{
public CurrentAccount()
{
friendlyName = "current account";
}
}
【问题讨论】:
-
您可以将friendlyName设为抽象,以便所有派生类都必须从它继承,或者将其设为虚拟(可选)
-
感谢@GHDevOps!然而,为了使其抽象,它不能是一个字段,它必须是一个受保护的属性,对吧?
-
你可以让它受保护:受保护的抽象字符串friendlyName {get;set;}
标签: c# oop coding-style