在派生类中不使用方法

本文关键字:使用方法 派生 | 更新日期: 2023-09-27 18:30:39

Uni 赋值要求我们在 C# 中构建一个从 Ingredient 派生Sauce的披萨应用程序。我有一个存储两种类型的对象的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 重写修饰符扩展基类方法,新修饰符隐藏它。

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

In Sauce.cs,

改变:

public new string GetInstructions()

自:

public override string GetInstructions()

new 关键字基本上会忽略基定义,并创建一个全新的方法,也称为 GetInstructions ,隐藏你在基类中定义的虚拟方法。 执行此操作时,您已经破坏了多态性。

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