父类属性
本文关键字:属性 父类 | 更新日期: 2023-09-27 17:57:33
如果我有一个父类或接口和 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 = "";
我会稍微
改变一下@itsme86方法,以便我只在一个特定的ContactInfo
上Address
或Telephone
:
public class Customer<T> where T : IContactInfo
{
public string Name { get; }
public T ContactInfo { get; }
}
public interface IContactInfo
{ }
public class GoldContactInfo : IContactInfo
{
public string Address { get; }
}
public class SilverContactInfo : IContactInfo
{
public string Telephone { get; }
}
public class GoldCustomer : Customer<GoldContactInfo>
{
// Here does the GoldCustomer have a GoldContactInfo
}
public class SilverCustomer : Customer<SilverContactInfo>
{
// Here does the SilverCustomer have a SilverContactInfo
}
我可能会选择一组单独的类,而不是使用继承,其中包含客户类型的不同联系信息:
public class Customer
{
public string Name { get; }
public ContactInfo ContactInfo { get; }
// Other common properties
}
public abstract class ContactInfo
{
public virtual string Address => "";
public virtual string Telephone => "";
}
public class GoldContactInfo : ContactInfo
{
public override string Address { get; }
}
public class SilverContactInfo : ContactInfo
{
public override string Telephone { get; }
}
在考虑继承和属性时,最简单的方法是用"is-a"和"has-a"来考虑它们。
Customer
有Address
吗? Telephone
怎么样? 如果一般Customer
没有地址,则以下内容毫无意义:
Customer c = new GoldCustomer();
c.Address = ""; // Customer does not have an Address property
实际对象确实具有 Address
属性这一事实无关紧要。 您已将其声明为 Customer
变量,因此编译器会将其视为 变量。
如果所有客户都有地址和电话,那么还有哪些其他属性或行为使SilverCustomer
与"普通"客户不同? 您可能还会发现指示级别的属性 Custmoer
也更简单,但这取决于实际使用情况。