主要还是参考微软的说明,原文:http://msdn.microsoft.com/zh-cn/library/ms173153.aspx
以下是我的理解:
一、BaseClass(父类、基类):
- orverride BaseClass 中的方法必须声明为 virtual,否则会出现编译错误;
- new BaseClass 中的方法声明或不声明为 virtual 均可。
二、ChildClass(子类)
- orverride ChildClass 中的方法必须声明为 orverride,否则会出现编译错误;
- new BaseClass 中的方法声明或不声明为 new 均可。
大部分情况下,new 和 orverride 处理逻辑是一致的,即调用子类的方法。唯独在 “多态” 这种情况:
BaseClass item = new DerivedClass();
item 调用方法时,如果子类中的方法是用 new 声明的,会调用基类的方法,但如果是 orverride 声明的,则会调用子类的方法,这应该是正确的效果。
微软的例子很经典:
using System;
using System.Text;
namespace OverrideAndNew
{
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
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();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
}