public class MyBaseClass //基类 { public virtual void Print() { Console.WriteLine("This is a base class."); } }
有三个类,形成了一个继承的层次:MyBaseClass、MyDerivedClass、SecondDerived,所有这三个类都包括名称 为Print的方法。在MyBaseClass中,Print被标记为virtual,在MyDerivedClass被标记为override。
public class MyDerivedClass:MyBaseClass //派生类 { public override void Print() { Console.WriteLine("This is a derived class"); } }
如果把SecondDerived的Print方法声明为override,那么它会覆写方法的全部两个低继承级别的版本,即通过基类调用时,基类会调用派生类的override方法,一直向上继承直到不是override方法为止。
public class SecondDerived:MyDerivedClass //最派生类 { public override void Print() { Console.WriteLine("This is a second derived class."); } }
public static void Main() //主类 { SecondDerived derived = new SecondDerived(); MyBaseClass mybc = (MyBaseClass)derived; derived.Print(); mybc.Print(); }
输出结果:This is a second derived class.
This is a second derived class.(MyBaseClass类调用MyDerivedClass,MyDerivedClass调用SecondDerived类中的方法,因为BaseClass的Print方法是virtual,MyDerivedClass、SecondDerived的Print方法是override,一直递归向派生类调用,直到派生类中的方法不是override为止。)
如果把SecondDerived的Print方法声明为new.
public class SecondDerived:MyDerivedClass //最派生类 { public new void Print() { Console.WriteLine("This is a second derived class."); } }
public static void Main() //主类 { SecondDerived derived = new SecondDerived(); MyBaseClass mybc = (MyBaseClass)derived; derived.Print(); mybc.Print(); }
输出结果:This is a second derived class.
This is a derived class.(基类BaseClass调用派生类MyDerivedClass的Print方法,因为BaseClass的Print方法是virtual,MyDerivedClass的Print方法是override,而没有调用SecondDerived类中的方法,因为SecondDerived类中的方法是new.)