且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么C#编译器没有故障代码,其中一个静态方法调用一个实例方法?

更新时间:2022-03-17 23:15:12

对于一些因此,重载决议总会发现之前的***匹配的 检查静态与非静态的。请试试这个代码与所有静态类型:

For some reason, overload resolution always finds the best match before checking for static versus non-static. Please try this code with all static types:

class SillyStuff
{
  static void SameName(object o) { }
  void SameName(string s) { }

  public static void Test()
  {
    SameName("Hi mom");
  }
}

这不能编译,因为***的过载是一个服用字符串。但是,嘿,这是一个实例方法,所以编译器抱怨(而不是采取次优过载)

This will not compile because the best overload is the one taking a string. But hey, that's an instance method, so compiler complains (instead of taking the second-best overload).

增加:所以我觉得动态例如原来的问题是,为了保持一致,当类型是动态的,我们也第一找到***的过载(只检查参数号和参数类型等等,而不是静态还是非静态),只有,然后检查静态的。但是,这意味着静态检查要等到运行时。因此,观察到的行为。

Addition: So I think the explanation of the dynamic example of the Original Question is that, in order to be consistent, when types are dynamic we also first find the best overload (checking only parameter number and parameter types etc., not static vs. non-static), and only then check for static. But that means that the static check has to wait until runtime. Hence the observed behavior.

此外晚期://博客:为什么他们选择做的事情这个有趣的顺序可以从的this博客文章由埃里克利珀的。

Late addition: Some background on why they chose to do things this funny order can be inferred from this blog post by Eric Lippert.