编译器选错了重载

6 c# asp.net polymorphism inheritance

好吧,我有一个派生类,它对我的​​基类上的方法有一个重载.我调用我认为与基类的方法签名匹配的东西,而是调用我的派生类实现.(下面的代码总是打印出"MyDerived")这是为什么?

    public class MyBase
    {
        public void DoSomething(int a)
        {
            Console.WriteLine("MyBase");
        }
    }

    public class MyDerived : MyBase
    {
        public void DoSomething(long a)
        {
            Console.WriteLine("MyDerived");
        }
    }


Main()
{
    MyDerived d = new MyDerived();
    d.DoSomething((int)5);
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*ell 5

大多数人认为基类上的DoSomething(int)重载比DoSomething(long)重载更好.

但是,由于变量是派生类型,因此将调用该版本的DoSomething..NET运行时始终支持最派生的编译时类型.

如果它找到一个可以在派生类型上工作的方法签名,它将在移动到任何基类方法之前使用它.通常,应避免重载基类中定义的方法.


Eri*_*ert 5

您描述的行为是正确的.许多人认为它违反直觉,但它经过精心设计,以防止脆弱的基类失败.

有关详细信息,请参阅我关于此主题的文章.

http://blogs.msdn.com/b/ericlippert/archive/2007/09/04/future-breaking-changes-part-three.aspx