重载方法中的 StackOverflowException
我试图在这样的代码中调用重载方法:
public abstract class BaseClass<T>
{
public abstract bool Method(T other);
}
public class ChildClass : BaseClass<ChildClass>
{
public bool Method(BaseClass<ChildClass> other)
{
return this.Method(other as ChildClass);
}
public override bool Method(ChildClass other)
{
return this == other;
}
}
class Program
{
static void Main(string[] args)
{
BaseClass<ChildClass> baseObject = new ChildClass();
ChildClass childObject = new ChildClass();
bool result = childObject.Method(baseObject);
Console.WriteLine(result.ToString());
Console.Read();
}
}
一切看起来都不错,但抛出了 StackOverflowException。 根据我的理解,如果我调用重载方法,那么应该调用最具体的方法版本,但在这种情况下,调用 Method(BaseClass
而不是 Method(ChildClass other) )
。
但是当我使用演员表时:
return ((BaseClass<ChildClass>)this).Method(other as ChildClass);
一切都按预期进行。 我错过了什么吗?或者这是 .NET 中的一个错误? 在.NET 2.0、3.5、4.0中测试
I'm trying to call overloaded method in code like this:
public abstract class BaseClass<T>
{
public abstract bool Method(T other);
}
public class ChildClass : BaseClass<ChildClass>
{
public bool Method(BaseClass<ChildClass> other)
{
return this.Method(other as ChildClass);
}
public override bool Method(ChildClass other)
{
return this == other;
}
}
class Program
{
static void Main(string[] args)
{
BaseClass<ChildClass> baseObject = new ChildClass();
ChildClass childObject = new ChildClass();
bool result = childObject.Method(baseObject);
Console.WriteLine(result.ToString());
Console.Read();
}
}
Everything looks ok, but the StackOverflowException is thrown.
In my understanding if i call overloaded method, then the most specific method version should be called, but in this case the Method(BaseClass<ChildClass> other)
is called instead of Method(ChildClass other)
.
But when i use a cast:
return ((BaseClass<ChildClass>)this).Method(other as ChildClass);
everything works as expected.
Am i missing somethig? Or this is a bug in .NET?
Tested in .NET 2.0,3.5,4.0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C# 规范第 7.3 节 指出:
由于两种方法都适用,但其中一种方法被标记为覆盖,因此在确定要调用哪个方法时将忽略它。因此,当前方法被调用,导致递归。当您进行转换时,覆盖的版本是唯一适用的方法,因此您可以获得所需的行为。
Section 7.3 of the C# spec states:
Since both methods are applicable, but one of them is marked as override, it is ignored for the purposes of determining which method to call. Thus the current method is invoked, leading to your recursion. When you make the cast, the overridden version is the only applicable method, and so you get the desired behaviour.