简体   繁体   English

使用可选参数和命名参数解决歧义

[英]Resolving Ambiguities with Optional Parameters and Named Arguments

I have two methods on my project as defined below: 我的项目中有两种方法,定义如下:

void Person(int ID, double height = 0.0, string team = "Knights")
{
   //my codes
}
void Person(int ID, double height = 0.0, string team = "Knights", int age = 30)
{
   //my codes
}

This is where I'm calling the method: 这是我调用方法的地方:

Person(1, 2.5, "Dark Ghost"); //calls first method

I didn't get any error when I built the project however I'm confused why above calls the first method? 构建项目时没有出现任何错误,但是我很困惑为什么上面调用了第一个方法?

and : 和:

Person(1, 46.5);   //compiler error. 

The C# specification says in §7.5.3.2, regarding choosing a better overload: C#规范在§7.5.3.2中说明,有关选择更好的重载:

If all parameters of [Method A] have a corresponding argument whereas default arguments need to be substituted for at least one optional parameter in [Method B] then [Method A] is better than [Method B]. 如果[方法A]的所有参数都有对应的自变量,而在[方法B]中需要用默认参数替换至少一个可选参数,则[方法A]比[方法B]更好。

When you specify a value for all parameters: 为所有参数指定值时:

Person(1, 2.5, "Dark Ghost");

The above rule makes the first method a better candidate, and it is chosen as the correct overload. 上面的规则使第一种方法成为更好的选择,并选择它作为正确的重载。

When you don't: 不这样做时:

Person(1, 46.5);

The rule does not apply, and the overload resolution is ambiguous. 该规则不适用,并且重载解决方案不明确。


You might say, why not choose the one with the least parameters? 您可能会说,为什么不选择参数最少的那个呢? That seems fine at first, but causes a problem when you have something like this: 乍一看似乎不错,但是当您遇到类似问题时会导致问题:

void Foobar(int a, string b = "foobar")
{
}

void Foobar(int a, int b = 0, int c = 42)
{
}

...

Foobar(1);

In this case there's no valid reason to choose the first one over the second. 在这种情况下,没有正当理由选择第二个。 Thus you can only properly resolve this by supplying a value for all parameters. 因此,您只能通过为所有参数提供一个值来正确解决此问题。

If possible, the one which can be applied without default parameters is called. 如果可能,将调用无需默认参数即可应用的一种。

In the first case 在第一种情况下

Person(1, 2.5, "Dark Ghost");

First method is called. 第一种方法被调用。

In the second case: 在第二种情况下:

Person(1, 46.5);

It will simply result in build error. 这只会导致构建错误。 "The call is ambiguous between the following methods or properties: Test.Person(int, double, string) and Person(int, double, string, int)". “在以下方法或属性之间的调用是不明确的:Test.Person(int,double,string)和Person(int,double,string,int)”。

TL:DR The first method (most specific) will be called because in that case no parameter needs to be bound using default values. TL:DR将调用第一个方法(最具体的方法),因为在这种情况下,无需使用默认值绑定任何参数。

For an in-depth discussion refer to this article . 有关深入讨论,请参阅本文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM