编译器选择了错误的重载

问题描述 投票:0回答:2

好吧,我有一个派生类,它对我的基类上的方法有重载。我调用了我认为与基类的方法签名匹配的内容,但调用了我的派生类实现。 (下面的代码总是打印出“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);
}
c# asp.net inheritance polymorphism
2个回答
5
投票

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

但是,由于变量是派生类型,因此将调用该版本的 DoSomething。 .NET 运行时始终青睐“最派生的编译时类型”。 如果它找到适用于派生类型的方法签名,它将在转移到任何基类方法之前使用该方法签名。 一般来说,您应该

避免重载基类中定义的方法


5
投票

请参阅我关于该主题的文章了解更多详细信息。

https://learn.microsoft.com/en-us/archive/blogs/ericlippert/future-writing-changes-part- Three

© www.soinside.com 2019 - 2024. All rights reserved.