C#: Any way to skip over one of the base calls in polymorphism?(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#:有什么方法可以跳过多态性中的一个基本调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#:有什么方法可以跳过多态性中的一个基本调用?
				
        
 
            
        - 输入按键事件处理程序 2022-01-01
 - MoreLinq maxBy vs LINQ max + where 2022-01-01
 - 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
 - 如何用自己压缩一个 IEnumerable 2022-01-01
 - 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
 - WebMatrix WebSecurity PasswordSalt 2022-01-01
 - C#MongoDB使用Builders查找派生对象 2022-09-04
 - C# 中多线程网络服务器的模式 2022-01-01
 - Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
 - 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
 
						
						
						
						
						
				
				
				
				