当从子类转换为父类来执行方法时,并不是直接编译执行,而是先看该方法是不是虚方法:
①、如是虚方法,则从该对象的实际类型(该子类)开始向 System.Object 回溯,直至找到该方法,再编译执行
②、如不是虚方法,则从直接从该父类开始搜索并向 System.Object 回溯,直至找到该方法,再编译执行
public interface IA { string SayHello(); } public class A : IA { public virtual string SayHello() { return "A"; } } public class B : A { public new virtual string SayHello() { return "B"; } } public class C : A { public override string SayHello() { return "C"; } } public class D : B { public override string SayHello() { return "D"; } } IA ia = new A(); IA ib = new B(); IA ic = new C(); IA id = new D(); ia.SayHello();//"A" ib.SayHello();//"A" ic.SayHello();//"C"//原回答这儿有误 id.SayHello();//"A" A a = new A(); A b = new B(); A c = new C(); A d = new D(); a.SayHello();//"A" b.SayHello();//"A" c.SayHello();//"C" d.SayHello();//"A" var va = new A(); var vb = new B(); var vc = new C(); var vd = new D(); va.SayHello();//"A" vb.SayHello();//"B" vc.SayHello();//"C" vd.SayHello();//"D"