【问题标题】:getDescription not working获取描述不起作用
【发布时间】:2016-02-04 14:04:23
【问题描述】:

为什么brink2.getDescription() 是Unkown Beverage 而brink3.getDescription() 是House Blend Coffe,

但brink2.cost()和brink3.cost()是1,09

为什么多态不起作用? 我的意思是为什么不叫drink2.getDescription() "return this.beverage.getDescription() + ", Mocha";"

我想得到: 饮料2.getDescription() 和饮料3.getDescription() 一样的结果

 class Program
{
    static void Main(string[] args)
    {

        Beverage beverage2 = new HouseBlend();
        beverage2 = new Mocha(beverage2);
        Console.WriteLine(beverage2.getDescription() + " $" + beverage2.cost());


        var beverage3 = new Mocha(new HouseBlend());
        Console.WriteLine(beverage3.getDescription() + " $" + beverage3.cost());
        Console.ReadKey();
    }
}

public abstract class Beverage
{
    public string description = "Unkown Beverage";

    public string getDescription()
    {
        return description;
    }

    public abstract double cost();
}

public abstract class CondomenentDecorator : Beverage
{
    public abstract string getDescription();
}



public class HouseBlend : Beverage
{
    public HouseBlend()
    {
        description = "House Blend Coffe"; 
    }

    public override double cost()
    {
        return .89;
    }
}

public class Mocha : CondomenentDecorator
{
    Beverage beverage;

    public Mocha(Beverage beverage)
    {
        this.beverage = beverage;
        this.beverage.description = beverage.description;
    }

    public override string getDescription()
    {
        return this.beverage.getDescription() + ", Mocha";
    }

    public override double cost()
    {
        return .20 + beverage.cost();
    }
}

【问题讨论】:

  • 多态性正在工作,但你的类层次结构有点倒退。您应该在基类中有抽象的 getDescription,而不是(重新)在层次结构中进一步引入它。

标签: c# oop


【解决方案1】:

因为编译器会警告你:

'CondomenentDecorator.getDescription()' 隐藏继承的成员'Beverage.getDescription()'。如果打算隐藏,请使用 new 关键字。

所以你没有覆盖那个方法。因此,如果从基类调用它,它会从基类返回值。

您不应在CondomenentDecorator 中定义abstract 方法,因为它已经派生自Beverage

此外,为了能够从Beverage 覆盖getDescription,应定义getDescription virtual

public virtual string getDescription() { }

【讨论】:

    猜你喜欢
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多