【问题标题】:C# Overloaded method invocation with Inheritance [duplicate]使用继承的 C# 重载方法调用 [重复]
【发布时间】:2013-04-25 10:49:23
【问题描述】:

我想知道调用打印“double in derived”的方法的原因是什么。我在 C# 规范中没有找到任何线索。

public class A
{
    public virtual void Print(int x)
    {
        Console.WriteLine("int in base");
    }
}

public class B : A
{
    public override void Print(int x)
    {
        Console.WriteLine("int in derived");
    }
    public void Print(double x)
    {
        Console.WriteLine("double in derived");
    }
}



B bb = new B();
bb.Print(2);

【问题讨论】:

  • 我可以破译7.4.2.2和7.4.2.3的规则,你可能比我聪明,但它会在某个地方。
  • @spender,它可能在里面,但是写得不好:)。
  • 这个问题已经回答了。看到这个线程:stackoverflow.com/questions/2821620/…
  • @cvraman,即使给出相同的结果,该示例也略有不同。在这种情况下,整数文字也是 object 类型的(正在发生扩大转换)。然而,在上面给出的示例中,发生了隐式转换(从 int 到 double。)

标签: c# inheritance overloading


【解决方案1】:

直接来自 C# 规范(7.5.3 重载分辨率):

方法调用的候选集合不包括标记为覆盖的方法(第 7.4 节),并且 如果基类中的任何方法不是候选方法派生类适用 (§7.6.5.1)。

在您的示例中,覆盖 Print(int x) 不是候选对象,Print(double x) 是适用的,因此无需考虑基类中的方法即可选择它。

【讨论】:

    【解决方案2】:

    编译器查看在最派生类中新声明的方法(基于表达式的编译时类型),并查看是否有适用的方法。如果是,它会使用“最好的”可用的。

    查看这个问题的答案:

    Different behaviour of method overloading in C#

    【讨论】:

    • 请引用并附上原始答案的链接。谢谢。
    • 添加了指向上述答案的链接,其中引用来自
    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 2015-08-04
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多