试图避免类结构中的多个子类型

时间:2012-02-24 16:34:01

标签: c# c#-4.0 inheritance interface base-class

我有两个抽象类Business&人。问题是我有一个可以是商业或个人的客户类型。有没有办法对此进行建模,以便我没有CustomerBusiness和CustomerPerson类?多重继承不是一种选择,因为这是C#。我一直在看这个,所以我看不到森林里的树木了。

public abstract class Business {
  public string Name { get; set; }
}

public abstract class Person {
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string MiddleName { get; set; }
  public DateTime? BirthDate { get; set; }
  public string Comments { get; set; }
}

public class CustomerBusiness : Business, CustomerRoles {
  public bool BillTo { get; set; }
  public bool ShipTo { get; set; }
  public bool DeliverTo { get; set; }
  public EntityType Type { get; set; }
}

public class CustomerPerson : Person, CustomerRoles {
  public bool BillTo { get; set; }
  public bool ShipTo { get; set; }
  public bool DeliverTo { get; set; }
  public EntityType Type { get; set; }
} 

public interface CustomerRoles {
  bool BillTo { get; set; }
  bool ShipTo { get; set; }
  bool DeliverTo { get; set; }
}

2 个答案:

答案 0 :(得分:2)

BusinessPerson类“prefer composition over inheritance可以ICustomerRoles而不是”ICustomerRoles

public class Business
{
    public string Name { get; set; }

    public ICustomerRoles CustomerRoles { get; set; }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public DateTime? BirthDate { get; set; }
    public string Comments { get; set; }

    public ICustomerRoles CustomerRoles { get; set; }
}

答案 1 :(得分:1)

我会说你的错误顺序是你的heirarchy。客户应该是基类,然后业务和人员应该是Customer类的实现。我确信除了CustomerRoles界面中的客户之外,所有类型的客户都有更多的客户属性。

我原以为会有类似CustomerCode等的东西。另外你可以说所有客户都有一个Name属性,并且由每个子类中的getter决定返回适当的值。因为在Business中有一个名为Name的属性,而一个人将拥有FirstName,MiddleName,Surname和Name属性,它们将以某种方式连接这些属性。