【问题标题】:Parent method with the proper data type is not getting invoked, if called from Child instance [duplicate]如果从子实例调用,则不会调用具有正确数据类型的父方法[重复]
【发布时间】:2019-06-20 18:50:09
【问题描述】:

代码:

class Program
{
    class A
    {
        public void abc(int x)
        {
            Console.WriteLine("abc from A");
        }
    }
    class B : A
    {
        public void abc(double x)
        {
            Console.WriteLine("abc from B");
        }
    }
    static void Main(string[] args)
    {
        B b = new B();
        b.abc(100);
        Console.ReadLine();
    }
}

从 B 类实例调用 abc() 方法时, 即使我们将整数数据(即 100)作为参数传递,为什么程序的执行还要使用 double 定义的方法参数? 请注意,在父类中已经为整数定义了一个方法。

为什么上面程序的输出是“abc from B”而不是“abc from A”。请多多指教。

【问题讨论】:

  • 另外,如果您将子类中的签名更改为例如字符串,则会调用父方法。 100 是一个有效的双精度数,因此调用了隐藏在 child 中的函数。

标签: c#


【解决方案1】:

您的方法已重载,并且您观察到这会导致您的类 B 中存在类似的方法解析,这将比继承类中的匹配方法首先选择。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-26
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多