c# - 继承抽象类——选择模式

标签 c# asp.net .net

我有一个抽象类是:

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 Quantityint 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 中的一些基本逻辑时,例如我不必更改每个子实现)

最佳答案

要实现这一点,您的 CountableQantable 必须派生自 Ingredient

public abstract class Countable : Ingredient 
{
   protected abstract int Count { get; set; }
}

public abstract class Qantable : Ingredient 
{
    protected abstract decimal Quantity { get; set; }
}

因此从 CountableQantable 派生的类也将是 Ingredient

关于c# - 继承抽象类——选择模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43001289/

相关文章:

c# - 为面试/测试做准备的关于 C++/STL/C#/J2SE 的最佳和最短书籍

c# - CaSTLe Windsor接口(interface)的多种实现

c# - 将 csv 格式的 .txt 文件作为工作表添加到 C# 中的现有工作簿

c# - 从自定义 HttpModule 中选择 HttpHandler

c# - 如何使用空格执行 linq 搜索

.net - obj 目录的用途

c# - 将项目从一个列表移到另一个

c# - c#/VB.net Property Properties 的优点/优势是什么 - Setters 的私有(private)访问修饰符

c# - 如何在 Windows 窗体中实例化大量按钮?

c# - 模型在 XML POST 上始终为 null