mic*_*ael 9 c# polymorphism inheritance overriding virtual-functions
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
}
}
Run Code Online (Sandbox Code Playgroud)
如上面的代码所示,我如何让Child.Foo()调用GrandParent.Foo()而不是进入Parent.Foo()?base.Foo()首先带我到Parent类.
Dan*_*mov 11
如果您需要,您的设计是错误的.
相反,将每类逻辑放入,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)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3433 次 |
| 最近记录: |