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#:有什么方法可以跳过多态性中的一个基本调用?


基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01