getDescription不起作用

时间:2016-02-04 14:04:24

标签: c# oop

为什么在drink2.getDescription()中有Unkown Beverage和beverage3.getDescription()是House Blend Coffe,

但drink2.cost()和beverage3.cost()是1,09

为什么多态不起作用? 我的意思是为什么drink2.getDescription()没有被称为“返回this.beverage.getDescription()+”,“摩卡”;“

我想得到: beverage2.getDescription()与drink3.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();
    }
}

1 个答案:

答案 0 :(得分:2)

因为编译器警告你:

  

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

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

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

另外,为了能够覆盖getDescription中的Beverage,应getDescription定义virtual

public virtual string getDescription() { }