Overloaded method selection logic

前端 未结 2 1380
面向向阳花
面向向阳花 2021-01-13 20:02

Given the following overloaded methods:

public string Test(long item)
{
    return \"Test with a long was called!\";
}

public string Test(int item)
{
    re         


        
相关标签:
2条回答
  • 2021-01-13 20:42

    The C# specification rules mean that the compiler prefers converting a short to int, not to object. I think this is due to the following rule from 7.5.3.5 Better conversion target (link is to C# 5 spec download, or see equivalent from C# 1.2 online)

    Given two different types T1 and T2, T1 is a better conversion target than T2 if at least one of the following holds:

    • An implicit conversion from T1 to T2 exists, and no implicit conversion from T2 to T1 exists
    • T1 is a signed integral type and T2 is an unsigned integral type. [other content omitted]

    To rewrite it for this scenario, since an implicit conversion from int to object exists, and no implicit conversion from object to int exists, converting to int is the better conversion.

    0 讨论(0)
  • 2021-01-13 20:51

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

    0 讨论(0)
提交回复
热议问题