C#:有什么方法可以跳过多态性中的一个基本调用? [英] C#: Any way to skip over one of the base calls in polymorphism?

查看:27
本文介绍了C#:有什么方法可以跳过多态性中的一个基本调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 类.


As the code above shows, how can I have the Child.Foo() make a call into GrandParent.Foo() instead of going into Parent.Foo()? base.Foo() takes me to the Parent class first.

推荐答案

如果你需要这个,你的设计是错误的.
相反,将每个类的逻辑放在 DoFoo 中,并且不要在不需要时调用 base.DoFoo.

Your design is wrong if you need this.
Instead, put the per-class logic in DoFoo and don't call base.DoFoo when you don't need to.

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)
    }
}

这篇关于C#:有什么方法可以跳过多态性中的一个基本调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆