Why doesn't the c# compiler check “staticness” of the method at call sites with a dynamic argument?

前端 未结 2 1698
失恋的感觉
失恋的感觉 2021-02-05 05:34

Why doesn\'t the C# compiler tell me that this piece of code is invalid?

class Program
{
    static void Main(string[] args)
    {
        dynamic d = 1;
                


        
2条回答
  •  無奈伤痛
    2021-02-05 06:32

    Overload resolution is dynamic here. Visible in this code snippet:

    class Program {
        public static void Main() {
            dynamic d = 1.0;
            MyMethod(d);
        }
    
        public void MyMethod(int i) {
            Console.WriteLine("int");
        }
    
        public static void MyMethod(double d) {
            Console.WriteLine("double");
        }
    }
    

    Works fine. Now assign 1 to d and note the runtime failure. The compiler cannot reasonably emulate dynamic overload resolution at compile time, so it doesn't try.

提交回复
热议问题