且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-30 22:20:04

关于选择更好的重载,C#规范在§7.5.3.2中进行了说明:

The C# specification says in §7.5.3.2, regarding choosing a better overload:

如果[方法A]的所有参数都有对应的参数,而[方法B]中的默认参数需要替换为至少一个可选参数,则[方法A]优于[方法B].

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].

为所有参数指定值时:

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

以上规则使第一种方法成为更好的选择,并被选择为正确的重载.

The above rule makes the first method a better candidate, and it is chosen as the correct overload.

不这样做时:

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.