为什么f(double)比f(long, int=0)更适合f(long)
本文关键字:long int 为什么 double | 更新日期: 2023-09-27 17:50:56
我的一个同事发现了这种奇怪的情况。我在这里贴一个简单的例子:
using System;
namespace Test
{
public class F
{
public void f(double d) { Console.WriteLine("public void F.f(double d)"); }
public virtual void f(long l, int q = 0) { Console.WriteLine("public virtual void F.f(long l, int q = 0)"); }
}
public class FDerived : F
{
public override void f(long l, int q) { Console.WriteLine("public override FDerived.f(long l, int q)"); }
public void g() { f(2L); }
}
public class G : FDerived
{
public void h1() { F fd = new FDerived(); fd.f(2L); }
public void h2() { FDerived fd = new FDerived(); fd.f(2L); }
}
class Program
{
static void Main(string[] args)
{
new FDerived().g();
new G().h1();
new G().h2();
Console.ReadLine();
}
}
}
示例的输出是:
public void F.f(double d)
public override FDerived.f(long l, int q)
public void F.f(double d)
我不明白这有什么意义。
为什么f(double)比f(long, int=0)更适合f(long)?为什么它取决于'fd'的类型?!
我这里没有c#规范,但是可选的参数值不会被重写的方法继承。
尝试更改FDerived
public override void f(long l, int q)
public override void f(long l, int q = 0)
,它将按预期工作。
请注意,这可以在一个简单的示例中显示:
public class F
{
public virtual void f(long l, int q = 0) { Console.WriteLine("public virtual void F.f(long l, int q = 0)"); }
}
public class FDerived : F
{
public override void f(long l, int q) { Console.WriteLine("public override FDerived.f(long l, int q)"); }
}
// Doesn't compile: No overload for method 'f' takes 1 arguments
new FDerived().f(5L);
显然这是编译:
new F().f(5L);
甚至这个
F obj = new FDerived();
obj.f(5L);
(这个将输出public override FDerived.f(long l, int q)
)