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

折月煮酒 提交于 2019-12-20 11:21:54

问题


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;
        MyMethod(d);
    }

    public void MyMethod(int i) 
    {
        Console.WriteLine("int");
    }
}

The call to MyMethod fails at runtime because I am trying to call a non-static method from a static method. That is very reasonable, but why doesn't the compiler consider this an error at compile time?

The following will not compile

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

so despite the dynamic dispatch, the compiler does check that MyMethod exists. Why doesn't it verify the "staticness"?


回答1:


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.




回答2:


When the compiler found the operation on/with variable of type dynamic, it will emit that information using CallSite object. (The CallSite object is store information about the call.)

In your first sample it can compile because the compiler can emit the information (e.g. type of call, method you want to call etc.). In the second code, you try to call method that doesn't exist so the compiler cannot emit IL code for you.



来源:https://stackoverflow.com/questions/8105879/why-doesnt-the-c-sharp-compiler-check-staticness-of-the-method-at-call-sites

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