Okay I have a derived class that has an overload to a method that's on my base class. I call what I think would match the method signature of the base class but instead my derived classes implementation is called. (The code below always prints out "MyDerived") Why is this?

    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);
}
有帮助吗?

解决方案

Most people assume the DoSomething(int) overload on the base class is a better match than the DoSomething(long) overload.

However, since the variable is a derived type, that version of DoSomething will be called. The .NET runtime always favors the most-derived compile-time type.

If it finds a method signature that will work on the derived type it will use that before moving to any of the base class methods. In general, you should avoid overloading methods defined in base classes.

其他提示

The behaviour you describe is correct. Many people consider it to be counterintuitive but it is carefully designed to prevent a brittle base class failure.

See my article on the subject for more details.

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top