且构网

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

为什么C#编译器不是一个静态方法调用实例方法的故障代码?

更新时间:2023-02-14 15:07:30

原因,重载分辨率始终在之前找到匹配静态与非静态的***匹配。请尝试使用所有静态类型的代码:

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.

延迟添加:为什么他们选择做这个有趣的顺序的一些背景可以从 Eric Lippert的这篇博文

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