Overloaded method selection logic

前端 未结 2 1402
面向向阳花
面向向阳花 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.

提交回复
热议问题