重载方法选择逻辑 [英] Overloaded method selection logic
问题描述
由于以下重载方法:
公共字符串测试(长项)
{
返回有很长的测试被称为!;
}
公共字符串测试(INT项目)
{
返回测试用int叫!
}
公共字符串测试(对象的项目)
{
返回测试与对象叫!
}
当我称之为测试()
,路过一个短
,就像这样:
短的shortValue = 7;
VAR的结果=测试(的shortValue);
为什么值结果
等于测试用int叫!
而不是测试与被调用的对象!
?
为什么值结果等于用int测试被称为!,而不是测试与对象叫!
块引用>
要转换
INT
是更好比转换为对象
,所以超载服用INT
是好一个比服用对象
- 两者都适用的短
隐式转换为这两个INT
和对象
。 (过载以长
也适用,但转换到INT
是一个比更好的长
,也。)
请参阅一般超载规则的C#语言规范的第7.5.3和7.5.3.3为关于更好的转换的规则。有小点,在这里写他们全力以赴,因为他们是很长的 - 但最重要的方面是,有从
INT
到对象转换
但对象
没有转换INT
- 这样的转换INT
更具体,因此更好。
(Section数字是从C#4和C#5的版本。您也可以下载< A HREF =http://www.microsoft.com/en-us/download/details.aspx?id=7029相对=nofollow> C#5规格以Word格式)。
Given the following overloaded methods:
public string Test(long item) { return "Test with a long was called!"; } public string Test(int item) { return "Test with an int was called!"; } public string Test(object item) { return "Test with an object was called!"; }
When I call
Test()
, passing ashort
, like this:short shortValue = 7; var result = Test(shortValue);
Why is the value
result
equal to"Test with an int was called!"
, instead of"Test with an object was called!"
?解决方案Why is the value result equal to "Test with an int was called!", instead of "Test with an object was called!"?
The conversion to
int
is "better" than the conversion toobject
, so the overload takingint
is "better" than the one takingobject
- and both are applicable asshort
is implicitly convertible to bothint
andobject
. (The overload takinglong
is also applicable, but the conversion toint
is better than the one tolong
, too.)See section 7.5.3 of the C# language specification for general overloading rules, and 7.5.3.3 for the rules about "better conversions". There's little point in writing them all out here, as they're very long - but the most important aspect is that there's a conversion from
int
toobject
but no conversion fromobject
toint
- so the conversion toint
is more specific, and therefore better.(Section numbers are from the C# 4 and C# 5 versions. You can download the C# 5 spec in Word format.)
这篇关于重载方法选择逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!