gpt4 book ai didi

c# - 如果调用继承的重载,会调用什么方法?

转载 作者:行者123 更新时间:2023-12-02 01:10:58 25 4
gpt4 key购买 nike

假设我有这个:

class A { }
class B : A { }
class C : B { }

class Foo
{
public void Bar(A target) { /* Some code. */ }
}

class AdvancedFoo : Foo
{
public void Bar(B target)
{
base.Bar(target);
// Some code.
}
}

sealed class SuperiorFoo : AdvancedFoo
{
public void Bar(C target)
{
base.Bar(target);
// Some code.
}
}

如果我运行 new SuperiorFoo().Bar(new C()) 将调用哪个重载,为什么?我猜它会被级联调用,但我不知道为什么以及是否保证了这种行为。

已更新

因此,base. 可与 FooAdvancedFoo 一起用于 SuperiorFoo,所以哪一个将是打电话,为什么?

最佳答案

既然问题已经修改,就编辑我的答案。

快速跟踪显示以下内容:

Entering SuperiorFoo.Bar()
Entering AdvancedFoo.Bar()
Entering Foo.Bar()
Leaving Foo.Bar()
Leaving AdvancedFoo.Bar()
Leaving SuperiorFoo.Bar()

让我们谈谈发生的事情:

  1. SuperiorFoo.Bar() 调用其基本方法。由于 SF.Bar() 继承来自AdvancedFoo,它的基本方法是AdvancedFoo.Bar()。

  2. AdvancedFoo.Bar() 然后调用其基类,即 Foo.Bar(),因为AdvancedFoo 继承自 Foo()。

流程不会从 SF.Bar() 跳转到 Foo.Bar(),因为您可能需要中间类的行为。

如果我们从 AdvancedFoo 中删除该方法,则遍历会略有不同。 SuperFoo.Bar() 仍会调用其基方法,但由于 AdvancedFoo 不再隐藏 Foo.Bar() 方法,因此逻辑将跳转到 Foo.Bar() 方法。

关于c# - 如果调用继承的重载,会调用什么方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10634890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com