class GrandParent { public virtual void Foo() { ... } } class Parent : GrandParent { public override void Foo() { base.Foo(); //Do additional work } } class Child : Parent { public override void Foo() { //How to skip Parent.Foo and just get to the GrandParent.Foo base? //Do additional work } }
如上面的代码所示,我如何使Child.Foo()调用到GrandParent.Foo()而不是进入Parent.Foo()? base.Foo()首先将我带到Parent类.
解决方法
你的设计是错误的,如果你需要这个.
相反,将每类逻辑放在DoFoo中,不需要调用base.DoFoo.
相反,将每类逻辑放在DoFoo中,不需要调用base.DoFoo.
class GrandParent { public void Foo() { // base logic that should always run here: // ... this.DoFoo(); // call derived logic } protected virtual void DoFoo() { } } class Parent : GrandParent { protected override void DoFoo() { // Do additional work (no need to call base.DoFoo) } } class Child : Parent { protected override void DoFoo() { // Do additional work (no need to call base.DoFoo) } }