【问题标题】:Reassign a field in child classes (clean code)重新分配子类中的字段(干净的代码)
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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";
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-13
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2018-08-26
      • 1970-01-01
      相关资源
      最近更新 更多