c# parameter implicit conversion

℡╲_俬逩灬. 提交于 2020-01-01 12:02:12

问题


Having this code:

    class Program
    {
        static void Main(string[] args)
        {
            Check(3);
            Console.ReadLine();
        }

        static void Check(int i)
        {
            Console.WriteLine("I am an int");
        }

        static void Check(long i)
        {
            Console.WriteLine("I am a long");
        }

        static void Check(byte i)
        {
            Console.WriteLine("I am a byte");
        }    
    }

Why this code prints "I am an int" and not "I am a long" ?


回答1:


Why this code prints "I am an int" and not "I am a long" ?

Because the compiler goes through the rules of overload resolution, which are in the C# 5 spec, starting at section 7.5.3.

Both of those are applicable function members (i.e. they'd both be valid for the argument list) but the Check(int) method is "better" than the Check(long) method (section 7.5.3.2) because the type of the argument is int, and an identity conversion is "better" than a widening conversion (section 7.5.3.3).

Given an implicit conversion C1 that converts from an expression E to a type T1, and an implicit conversion C2 that converts from an expression E to a type T2, C1 is a better conversion than C2 if at least one of the following holds:

  • E has a type S and an identity conversion exists from S to T1 but not from S to T2
  • ...

Here E is int, T1 is int, and T2 is long. There's an identity conversion from int to int, but not from int to long... therefore this rule applies, and the conversion from int to int is better than the conversion from int to long.



来源:https://stackoverflow.com/questions/31662284/c-sharp-parameter-implicit-conversion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!