【问题标题】:Inheritance and types in C#C#中的继承和类型
【发布时间】:2021-04-06 10:52:34
【问题描述】:

我在允许员工或个人按照以下详细信息“拥有”帐户时遇到了一些麻烦。

在下面的 sn-p 中,在 Account 类中,我只接受 Person 作为所有者。我有点需要接受StaffPerson

我的主要问题是,稍后在方法applyFee() 中,我需要联系所有者对象,如果所有者有 feeDiscount 属性,我将需要使用它来计算。 我的问题是,因为在 Account 类中,类型是 Person owner,所以我没有得到 feeDiscount,因为它是空的。

class Person
{
  public string name;

  public Person(string newName)
  {
    name = newName;
  }
}

class Staff : Person
{
  public decimal feeDiscount;

  public override Staff(string newName)
  {
    name = newName;
    feeDiscount = 0.5;
  }

}

class Account
{
  private decimal balance = 1000;
  private Person owner;
  public Account(Person newOwner)
  {
    owner = newOwner;
  }

  public void applyFee() {

    decimal fee = 100;

    if (owner != null)
    {

      if (owner.feeDiscount) {
        balance = balance - (fee * owner.feeDiscount);
      } else {
        balance = balance - fee;
      }

    }
  }
}

class Program
{
  static void Main(string[] args)
  {

    Person person1 = new Person("Bob");
    Staff staff1 = new Staff("Alice");

    Account account1 = new Account(person1);
    Account account2 = new Account(staff1);

    account1.applyFee();
    account2.applyFee();
  }
}

【问题讨论】:

  • 最简单的解决方案是给你的Person 一个feeDiscount1
  • @canton7 对不起,我弄错了!你第一次是对的
  • @MatthewWatson 哦,不,我错过了现在改回来的编辑窗口!
  • 他们是对的,0 的费用折扣将导致100 * 0,实际上是 100% 的折扣

标签: c# oop


【解决方案1】:

如果您希望 Person 尽可能保持通用,那么您可以创建另一个名为 customer 的类,该类的 feeDiscount 为 0。

因此,任何有业务在商店花钱的人都有一些feeDiscount。这样,您可以将applyFee 转为CustomerStaff,但不能转为Person

【讨论】:

  • 如何定义 Account 类中的所有者可以是客户或员工?我发现的方法是使用 Person private Person owner; 但不确定这是否正确。
  • 你可以保持原样并相信Account 只被喂给StaffCustomers,或者你可以创建Person 和抽象类,上面写着Person can'不能只是一个Person,它只能用作定义其他类的基础,如CustomerStaff
猜你喜欢
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 2010-11-08
相关资源
最近更新 更多