在C#中,override和new都会覆盖父类中的方法。那它们两者之前有什么区别呢?
- override是指“覆盖”,是指子类覆盖了父类的方法。子类的对象无法再访问父类中的该方法。
- new是指“隐藏”,是指子类隐藏了父类的方法,当然,通过一定的转换,可以在子类的对象中访问父类的方法。
以下代码的运行结果是什么?
class Base
{
public virtual void F1()
{
Console.WriteLine("Base's virtual function F1");
}
public virtual void F2()
{
Console.WriteLine("Base's virtual fucntion F2");
}
}
class Derived:Base
{
public override void F1()
{
Console.WriteLine("Derived's override function F1");
}
public new void F2()
{
Console.WriteLine("Derived's new function F2");
}
}
class Program
{
public static void Main(string[] args)
{
Base b1 = new Derived();
//由于子类覆盖了父类的方法,因此这里调用的是子类的F1方法。也是OO中多态的体现
b1.F1();
//由于在子类中用new隐藏了父类的方法,因此这里是调用了隐藏的父类方法
b1.F2();
}
}
或者我们用以下的代码更加容易明白: class Program
{
public static void Main(string[] args)
{
Derived b1 = new Derived();
//由于子类覆盖了父类的方法,因此这里调用的是子类的F1方法。也是OO中多态的体现
((Base) b1).F1();
//由于在子类中用new隐藏了父类的方法,因此这里是调用了隐藏的父类方法
((Base) b1).F2();
}
}
以上两个的输出都为:
Derived's override function F1
Base's virtual fucntion F2
在上面的例子中,由于F1覆盖(override)了原先的方法,因此即使转成父类的对象,仍旧调用了子类的F1方法。而由于子类的F2方法只是“隐藏”了父类的F2方法,因此当强制转换成父类(Base)的对象去调用F2方法时,调用了原先隐藏的父类的F2方法。