【问题标题】:Compiler picking the wrong overload编译器选择错误的重载
【发布时间】:2014-06-02 11:28:33
【问题描述】:

好的,我有一个派生类,它对我的​​基类上的方法有重载。我称我认为与基类的方法签名匹配,而是调用我的派生类实现。 (下面的代码总是打印出“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);
}

【问题讨论】:

  • 对不起!我的意思是它会打印出 MyDerived!错字我现在改!

标签: c# asp.net inheritance polymorphism


【解决方案1】:

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

但是,由于变量是派生类型,因此将调用该版本的 DoSomething。 .NET 运行时总是偏爱派生最多的编译时类型

如果它找到一个适用于派生类型的方法签名,它将在移动到任何基类方法之前使用它。 一般来说,您应该避免重载基类中定义的方法

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多