重写、隐藏基类(new, override)的方法
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是一样的。