StackOverflowException in overloaded methods
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);
开发者_Python百科
everything works as expected. Am i missing somethig? Or this is a bug in .NET? Tested in .NET 2.0,3.5,4.0
Section 7.3 of the C# spec states:
First, the set of all accessible (Section 3.5) members named N declared in T and the base types (Section 7.3.1) of T is constructed. Declarations that include an override modifier are excluded from the set. If no members named N exist and are accessible, then the lookup produces no match, and the following steps are not evaluated.
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.
精彩评论