下面,您將找到我為模擬銀行帳戶的程式撰寫的代碼片段。
我想知道是否有更簡潔的方式來設計該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";
}
}
uj5u.com熱心網友回復:
您不能創建它,const因為它需要在宣告時進行初始化。您可以制作它readonly并將其設定在子建構式中,這將盡可能接近const非編譯時常量的值。
public abstract class Account
{
protected readonly string friendlyName;
// the rest is the same
}
uj5u.com熱心網友回復:
您可以將其設為抽象屬性。繼承非抽象類然后必須覆寫它
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";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/323890.html
