c# - 不使用派生类中的方法

标签 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;
    }

最佳答案

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

来自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;
    }

关于c# - 不使用派生类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34821609/

相关文章:

c# - 我如何使用 linq 和 c# 将字典字符串字符串转换为字符串和字符串的键值对数组

php - Laravel:从 Blade 模板调用 Controller 类的方法

类实现接口(interface)时PHP Trait冲突

java - 多态排序转换

c++ - 将指针传递给派生类,传递给需要指向基类的指针的函数?

Java OOP 优化代码

c# - Convert.ToDouble 和 double.Parse 与 InvariantCulture 的区别

c# - 将列表设置为本身是否会影响性能?

c# - CS 脚本评估器加载代码 : How to compile and reference a second script (reusable library)

c# - 接口(interface)中的重载方法