好吧,我有一个派生类,它对我的基类上的方法有重载。我调用了我认为与基类的方法签名匹配的内容,但调用了我的派生类实现。 (下面的代码总是打印出“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);
}
大多数人认为基类上的 DoSomething(int) 重载比 DoSomething(long) 重载更匹配。
但是,由于变量是派生类型,因此将调用该版本的 DoSomething。 .NET 运行时始终青睐“最派生的编译时类型”。 如果它找到适用于派生类型的方法签名,它将在转移到任何基类方法之前使用该方法签名。 一般来说,您应该
避免重载基类中定义的方法。