我定义了两个类,基类person。和派生类客户。 在派生类中,我重新编写了display()方法。 但我想在客户实例中调用基类(person)的显示方法。 我该如何处理?在C#中如何调用派生类实例中已在派生类中重写的基类方法
我知道在msdn中,有一些使用base()
来调用的例子,但我的问题是不在类定义中调用,而是在实例调用中调用。我认为这是不同的。
using System;
using System.Text;
class Program
{
static void Main(string[] args)
{
person myperson = new person();
myperson.DisplayInfo();
customer mycustomer = new customer();
mycustomer.DisplayInfo();
// --here I want to invoke person.display(). how to realize it?
//mycustomer.base.DisplayInfo();
}
public class person
{
public string Name="base name";
public virtual string DisplayInfo()
{
string msg = Name;
Console.WriteLine(msg);
return msg;
}
}
public class customer : person
{
public new void DisplayInfo()
{
Console.WriteLine("derive "+ Name);
}
}
}
你确定要'new'而不是'override'吗? – zerkms
避免为'DisplayInfo'使用'new'' –
“但我的问题不是在类定义中调用,而是在实例调用中”---你用它解决的真正问题是什么?这听起来像是一个糟糕的主意。 – zerkms