C#中方法有覆盖隐藏和override重写之分:
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
public void Method3() {
Console.WriteLine("Base - Method3");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
base.Method2();
Console.WriteLine("Derived - Method2");
}
public void Method3()
{
base.Method3();
Console.WriteLine("Derived - Method3");
}
}
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
bc.Method3();
Console.WriteLine("****************");
// Output:
// Base - Method1
// Base - Method2
// Base - Method3
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
dc.Method3();
Console.WriteLine("****************");
// Output:
// Derived - Method1
// Base - Method2
// Derived - Method2
// Base - Method3
//Derived - Method3
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
bcdc.Method3();
// Output:
// Derived - Method1
// Base - Method2
// Base - Method3
Console.Read();
}
}
在上面的定义中可以看出,override重写是指在子类中重写父类中方法的定义,在运行时是看实例化对象属于父类还是子类,如果是子类则运行的是子类中对该方法的定义。
而覆盖隐藏,父类中的方法并没有被修改,只是被隐藏了,运行时如果申明的对象是父类 那么该方法运行的是父类中的定义,如果申明的对象是子类,则运行的方法是子类中的定义。
总结:重写是对父类方法定义的重新定义,覆盖只是隐藏,父类和子类对同名方法都有各自的定义,所以运行时系统会优先选择调用者中的定义,在.NET平台下,子类实例化会先实例化父类,当子类对象赋给父类变量时,只会将父类的部分赋给父类,所以如果子类不是重写的父类的同名方法,其父类中的定义不会被修改,运行时父类调用的是父类中的定义,子类调用的是子类中的定义。