Thi*_*a H 22 .net c# oop wpf inheritance
当我尝试运行以下代码片段时,它正在执行错误的重载方法.我很困惑为什么这样做? [ testB.TestMethod(testValue)方法执行 public double TestMethod(double value)方法]
public class TestA
{
public int TestMethod(int value)
{
return value;
}
}
public class TestB : TestA
{
public double TestMethod(double value)
{
return value;
}
}
static void Main( string[] args )
{
TestB testB = new TestB();
int testValue = 3;
testB.TestMethod(testValue);
}
Run Code Online (Sandbox Code Playgroud)
你对此有什么想法吗?
有没有办法通过TestB实例调用TestA类方法而不强制转换为TestA.
但它不会发生在JAVA和C++中
Mar*_*ell 22
根据规范,在"过载分辨率"下:
...如果派生类中的任何方法适用,则基类中的方法不是候选者(第7.6.5.1节).
遗产
继承可能会导致混乱的影响.当编译器寻找实例方法重载时,它会考虑调用的"目标"的编译时类,并查看在那里声明的方法.如果它找不到合适的东西,那么它会查看父类...然后是祖父母类等.这意味着如果在层次结构的不同级别有两种方法,则首先选择"更深"的方法.即使它不是呼叫的"更好的功能成员".
来源:http://csharpindepth.com/Articles/General/Overloading.aspx