C#中的继承和类型

Fil*_*ype 1 c# oop

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

在下面的代码段中,在 Account 类中,我只接受Person作为所有者。我有点需要接受 aStaff或 aPerson

我的主要问题是,稍后在方法中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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*tuh 6

如果您想Person尽可能保持通用,那么您可以创建另一个名为customerwho 的类,其feeDiscount值为 0。

因此,任何有生意在商店花钱的人都会有一些feeDiscount. 这样,您可以applyFee对 aCustomer或 aStaff但不是 aPerson

  • 您可以将其保留原样,并相信“Account”仅提供给“Staff”和“Customers”,或者您可以创建“Person”和抽象类,其中表示“Person”不能只是一个“Person”,它只能用作定义其他类(如“Customer”或“Staff”)的基础。 (2认同)