方法在被调用时以递归方式调用自身

本文关键字:调用 方式 递归 方法 | 更新日期: 2023-09-27 18:25:02

我一直在通过C#读取CLR,我读取了以下内容:

有时,编译器会使用调用指令来调用虚拟方法,而不是使用callvirt指令。起初,这可能看起来令人惊讶,但下面的代码说明了为什么有时需要它:

internal class SomeClass {
// ToString is a virtual method defined in the base class: Object.
public override String ToString() {
// Compiler uses the ‘call’ IL instruction to call
// Object’s ToString method nonvirtually.
// If the compiler were to use ‘callvirt’ instead of ‘call’, this
// method would call itself recursively until the stack overflowed.
return base.ToString();
}
}

呼叫基地时。ToString(一个虚拟方法),C#编译器发出一条调用指令,以确保基类型中的ToString方法是非虚拟调用的。这是必需的,因为如果以虚拟方式调用ToString,则调用将递归执行,直到线程的堆栈溢出,这显然是不希望的。

虽然这里有解释,但我不明白为什么虚拟调用的ToString会递归执行。如果可能的话,有人能提供另一种解释或用更简单的方式描述它吗。

谢谢!

方法在被调用时以递归方式调用自身

使用base.ToString(),您实际上想要调用ToString()方法的基类实现。

如果您只是简单地调用this.ToString(),方法将被"虚拟"调用,即实际类的ToString()将被调用。

在您的示例中,如果base.ToString()将被"虚拟"调用,它将与this.ToString()相同——这将以ToString()方法再次调用相同的ToString()结束,因此将是一个以堆栈溢出结束的无限递归。