-1

下面,您将找到我为模拟银行账户的程序编写的代码片段。

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

2 回答 2

1

您无法制作它const,因为它需要在声明时进行初始化。您可以制作它readonly并将其设置在子构造函数中,这将尽可能接近const非编译时常量的值。

public abstract class Account
{
   protected readonly string friendlyName;
   // the rest is the same
}
于 2021-10-18T18:14:22.163 回答
0

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

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";
}
于 2021-10-18T18:39:07.350 回答