【发布时间】:2021-11-09 06:53:07
【问题描述】:
我最近注意到 C# 编译器允许方法重载,如下所示:
public static string foo(string a, bool x = false)
{
return "a";
}
public static string foo(string a)
{
return "b";
}
据我测试,只要没有给出第二个参数,它总是返回“b”,这是有道理的。但是,我认为编译器确实不应该允许这种类型的重载。请问为什么这个功能是这样设计的,而不是编译器报错?
【问题讨论】:
-
那么这个问题还是陈述?这实际上是 C# ECMA 规范中称为重载解析的一个非常深入的主题,它可以在编译或运行时发生。说某事应该以不同的方式工作是可以的(也许你已经以各种可以想象的方式完全考虑了这一点,所以他们应该聘请你加入 Roslyn 和运行时团队),但是我们无能为力
-
However, I think the compiler really should not allow this type of overloading.你为什么这么认为? -
Why could C# overload two methods with the same params as long as one of them has default param?显而易见的答案是它们没有具有相同的参数。 -
你可能会看到这种警告:
Method with optional parameter is hidden by overload. -
顺便说一句,我发现微软确实在他们的文档中声明了重载解决方案:docs.microsoft.com/en-us/dotnet/csharp/programming-guide/…
标签: c# overloading default-value