不在派生类中使用方法

时间:2016-01-15 23:28:37

标签: c# oop polymorphism

Uni分配要求我们在C#中构建一个从Sauce派生Ingredient的披萨应用。我有List<Ingredient>存储两种类型的对象。

Pizza.cs调用派生方法略有不同的方法GetInstructions()。不幸的是,永远不会调用Sauce.GetInstructions()。正如您所看到的那样,那里有一个调试行,当程序执行该例程时它应弹出一个消息框,但它没有弹出。任何人都可以建议为什么不呢?

Pizza.cs包含以下方法:

public string BuildInstructionList()
    {   // iterate through list of selected toppings and build a single string for display in the GUI
    int count = 1; string instructions = "";
    foreach (var i in toppings)
        {
        instructions = instructions += string.Format("Step {0}: {1}", count, i.GetInstructions());
        count++;
        }
        return instructions;
    }

Ingredient.cs包含:

public virtual string GetInstructions()
    {
        string instructionLine;
        string qty = this.GetIngredientQuantity().ToString();
        string unit = this.GetIngredientUnit();
        string name = this.GetIngredientName();
        instructionLine = string.Format("Add {0} {1} of {2} to the pizza.\n", qty, unit, name);
        return instructionLine;
    }

Sauce.cs包含:

public new string GetInstructions()
    {
        PizzaGUI.Message("I am here!");
        string instructionLine;
        string qty = this.GetIngredientQuantity().ToString();
        string unit = this.GetIngredientUnit();
        string name = this.GetIngredientName();
        instructionLine = string.Format("Apply {0} {1} of {2} to the pizza.\n", qty, unit, name);
        return instructionLine;
    }

2 个答案:

答案 0 :(得分:2)

您需要在Sauce.cs方法中使用override new

From MSDN override修饰符扩展基类方法,new修饰符隐藏它。

public override string GetInstructions()
    {
        PizzaGUI.Message("I am here!");
        string instructionLine;
        string qty = this.GetIngredientQuantity().ToString();
        string unit = this.GetIngredientUnit();
        string name = this.GetIngredientName();
        instructionLine = string.Format("Apply {0} {1} of {2} to the pizza.\n", qty, unit, name);
        return instructionLine;
    }

答案 1 :(得分:0)

在Sauce.cs中,

变化:

public new string GetInstructions()

要:

public override string GetInstructions()

new 关键字基本上会忽略基本定义,并创建一个名为GetInstructions的全新方法,隐藏您在基类中定义的虚方法。当你这样做时,你已经破坏了多态性。

我还建议将Ingredient类抽象化,而不是为GetInstructions定义实现。