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)。如果它没有预期的函数,它将使用基函数 因此:
- 在第一个程序中-
也适用于double,因此它可以使用派生函数(double)3
- 在第二个程序中,
对于int是可以的,但是3
对于int不是可以的。因此对于3.3
它必须使用基类的int函数3.3
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