次のようなコードでオーバーロードされたメソッドを呼び出そうとしています:
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<ChildClass> other)
代わりに が呼び出されMethod(ChildClass other)
ます。
しかし、キャストを使用する場合:
return ((BaseClass<ChildClass>)this).Method(other as ChildClass);
すべてが期待どおりに機能します。私は何かが欠けていますか?または、これは .NET のバグですか? .NET 2.0、3.5、4.0 でテスト済み