为什么编译器会自动转换而不进一步继承?

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节).

  • @JeppeStigNielsen确实,紧接在上面之前的单词(在"..."中)是:"......方法调用的候选集不包括标记为覆盖的方法(第7.4节)," (6认同)

Jer*_*gen 9

遗产

继承可能会导致混乱的影响.当编译器寻找实例方法重载时,它会考虑调用的"目标"的编译时类,并查看在那里声明的方法.如果它找不到合适的东西,那么它会查看父类...然后是祖父母类等.这意味着如果在层次结构的不同级别有两种方法,则首先选择"更深"的方法.即使它不是呼叫的"更好的功能成员".

来源:http://csharpindepth.com/Articles/General/Overloading.aspx

  • 因此,如果要在具有隐式兼容类型的`TestA`上调用具有相同名称的成员,则必须转换为`TestA`? (2认同)
  • @Charleh,是的,如果你想在`TestA`中调用重载,你必须将它转换为`TestA`.我测试了它. (2认同)