代碼如下:
public class Father
{
public void Write() {
Console.WriteLine("父");
}
}
public class Mother
{
public virtual void Write()
{
Console.WriteLine("母");
}
}
public class Boy : Father
{
public new void Write()
{
Console.WriteLine("子");
}
}
public class Girl : Mother
{
public override void Write()
{
Console.WriteLine("女");
}
}
代碼如下:
static void Main(string[] args)
{
Father father = new Boy();
father.Write();
Boy boy = new Boy();
boy.Write();
Mother mother = new Mother();
mother.Write();
Girl girl = new Girl();
girl.Write();
Console.ReadLine();
}
輸出:
父
子
母
女
添加調用父方法:
代碼如下:
public class Boy : Father
{
public new void Write()
{
base.Write();
Console.WriteLine("子");
}
}
public class Girl : Mother
{
public override void Write()
{
base.Write();
Console.WriteLine("女");
}
}
輸出:
父
父
子
母
母
女
可見,在程序運行結果上new 和override是一樣的。