在子类中重新分配字段(干净的代码)



下面是我为一个模拟银行账户的程序编写的代码片段。

我想知道是否有一种更干净的方法来设计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";
}
}

你不能让它为const,因为它需要在声明时初始化。您可以将其设置为readonly并在子构造函数中设置它,这样就可以使用非编译时常量的值尽可能接近const

public abstract class Account
{
protected readonly string friendlyName;
// the rest is the same
}

您可以将其设置为抽象属性。继承的非抽象类必须覆盖它

public abstract class Account
{
protected abstract string FriendlyName { get; }
...
}
public class SavingsAccount : Account
{
protected override string FriendlyName => "savings account";
}
public class CurrentAccount : Account
{
protected override string FriendlyName => "current account";
}

最新更新