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/