我有一个抽象类是:
public abstract class Ingredient
{
private string name;
private decimal price;
public Ingredient(string name, decimal price)
{
this.name = name;
this.price = price;
}
public string Name
{
get
{
return this.name;
}
}
protected decimal Price
{
get
{
return this.price;
}
}
protected void ChangePrice(decimal newPrice)
{
Console.WriteLine(string.Format("The price changed from {0} to {1} for engridient {2}", this.price, newPrice,this.name));
this.price = newPrice;
}
}
然后我有很多继承成分的成分:
Tomato:Ingredient {//implementation}
Cheese:Ingredient {//implementation}
Mushrooms:Ingredient {//implementation}
Onion:Ingredient {//implementation}
但我希望我的配料具有某种类型的测量值,可以是decimal Quantity
或 int Count
,具体取决于配料的类型。例如 Tomato 是可数的(3 个西红柿),奶酪是用 decimal Quantity
来衡量的(30 克奶酪)。我尝试制作抽象类:
public abstract class Countable
{
protected abstract int Count { get; set; }
}
public abstract class Qantable
{
protected abstract decimal Quantity { get; set; }
}
但是类不能有两个基类。(我不能有 Tomato:Ingredient, Countable {//implementation}
)我不能使用接口(interface),因为我希望我的测量值只可见对于子元素,我想封装测量(所以当我想更改 Countable 中的一些基本逻辑时,例如我不必更改每个子实现)
最佳答案
要实现这一点,您的 Countable
和 Qantable
必须派生自 Ingredient
。
public abstract class Countable : Ingredient
{
protected abstract int Count { get; set; }
}
public abstract class Qantable : Ingredient
{
protected abstract decimal Quantity { get; set; }
}
因此从 Countable
或 Qantable
派生的类也将是 Ingredient
。
关于c# - 继承抽象类——选择模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43001289/