重载方法选择逻辑 [英] Overloaded method selection logic

查看:155
本文介绍了重载方法选择逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下重载方法:

 公共字符串测试(长项)
{
返回有很长的测试被称为!;
}

公共字符串测试(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 a short, 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 to object, so the overload taking int is "better" than the one taking object - and both are applicable as short is implicitly convertible to both int and object. (The overload taking long is also applicable, but the conversion to int is better than the one to long, 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 to object but no conversion from object to int - so the conversion to int 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屋!

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