使用可选参数和命名参数解决歧义 [英] Resolving Ambiguities with Optional Parameters and Named Arguments

查看:50
本文介绍了使用可选参数和命名参数解决歧义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有两种方法,定义如下:

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?

和:

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

推荐答案

关于选择更好的重载,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.

这篇关于使用可选参数和命名参数解决歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆