【发布时间】:2016-07-18 14:34:48
【问题描述】:
如果我有一个父类或接口和 2 个从父类继承或实现接口的子类,并且我在父类中具有公共属性,但每个子类中都有一些不同的属性。我应该收集父类/接口中的所有属性还是将它们分开?
abstract class Customer
{
string name { get; set; }
}
class GoldCustomer : Customer
{
string Address { get; set;}
}
class SilverCustomer : Customer
{
string Telephone { get; set;}
}
如果我将它们分开并从父级创建指向子级的引用,那么我无法访问分离的子级属性
Customer c = new GoldCustomer();
c.Address // error
哪种架构更正确且不违反任何设计模式?
abstract class Customer
{
string name { get; set; }
string Address { get; set;}
string Telephone { get; set;}
}
class GoldCustomer : Customer
{
}
class SilverCustomer : Customer
{
}
Customer c = new GoldCustomer();
c.Address = "";
【问题讨论】:
-
这取决于具体情况。以不需要违反 Liskov 替换原则的方式设计类 (en.wikipedia.org/wiki/Liskov_substitution_principle) 如果您觉得这很困难,请考虑组合而不是继承 (en.wikipedia.org/wiki/Composition_over_inheritance)
-
这个问题太笼统了,正如 itsme86 所说,这取决于具体的情况。两种方法都可能是正确的,这实际上取决于您想要做什么。试着事先考虑一下你真正需要什么,这样你就不会产生不必要的依赖。
标签: c# inheritance interface polymorphism abstract-class