C# 带继承问题的重载

C# 带继承问题的重载,c#,C#,我有以下代码,它运行成功。但请仔细注意它的输出: using System; class Base { public int f(int i) { Console.Write("f (int): "); return i + 3; } } class Derived : Base { public double f(double i) { Con

我有以下代码,它运行成功。但请仔细注意它的输出:

using System;                    
class Base 
{ 
    public int f(int i) 
    { 
        Console.Write("f (int): "); 
        return i + 3; 
    } 
} 
class Derived : Base 
{ 
    public double f(double i) 
    { 
        Console.Write("f (double) : "); 
        return i+3.3; 
    } 
} 
class MyProgram 
{ 
    static void Main(string[] args) 
    { 
        Derived obj = new Derived(); 
        Console.WriteLine(obj.f(3)); 
        Console.WriteLine(obj.f(3.3)); 
        Console.ReadKey(); // write this line if you use visual studio 
    } 
} 
输出: f(int):6 f(双人):6.6
这是怎么可能的?

因为派生对象的默认函数是派生函数(在第一个程序中为-double,在第二个程序中为-int)。如果它没有预期的函数,它将使用基函数

因此:

  • 在第一个程序中-
    3
    也适用于double,因此它可以使用派生函数(double)
  • 在第二个程序中,
    3
    对于int是可以的,但是
    3.3
    对于int不是可以的。因此对于
    3.3
    它必须使用基类的int函数

在第一个示例中,编译器可以在数字类型之间进行简单的类型转换(
int
double
)。这使得
f(double)
函数成为可能的调用目标。编译器更愿意在可能的情况下调用派生类上的函数,因为派生类可能包含更具体的逻辑。基类可能包含更多的泛型逻辑,因此价值较低


在第二个示例中,派生类上的函数只能使用
int
参数调用。编译器选择此函数是因为它位于派生类上,即使基类上的函数也可能有效。当参数为
double

等一下,基类上的函数是唯一的选项,为什么您希望输出?你试过调试你的代码吗?这不是过载。这是
隐藏
。在
Base
类中隐藏
f
方法。当您启动
Derived
并调用
f
方法时。当然,
f
派生的
中的位置将给出答案。一个小错误:我会说有一个。
Output:

f(double) : 6.3
f(double):  6.6 


Expected Output:

f(int) : 6
f(double) : 6.6
using System;
namespace MyProgram
{
    class Base
    {
        public double f(double i)
        {
            Console.Write("f (double): ");
            return i + 3.3;
        }
    }
    class Derived : Base
    {
        public int f(int i)
        {
            Console.Write("f (int): ");
            return i + 3;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Derived obj = new Derived();
            Console.WriteLine(obj.f(3));
            Console.WriteLine(obj.f(3.3));
        }
    }
}
Output: f(int) : 6 f(double) : 6.6