为什么C#编译器没有故障代码,其中一个静态方法调用一个实例方法? [英] Why does the C# compiler not fault code where a static method calls an instance method?

查看:164
本文介绍了为什么C#编译器没有故障代码,其中一个静态方法调用一个实例方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码有一个静态方法,美孚(),调用一个实例方法,酒吧()

The following code has a static method, Foo(), calling an instance method, Bar():

public sealed class Example
{
    int count;

    public static void Foo( dynamic x )
    {
        Bar(x);
    }

    void Bar( dynamic x )
    {
        count++;
    }
}



它编译没有错误*而是生成一个运行时绑定异常在运行时。删除动态参数,这些方法会导致编译器错误,符合市场预期。

It compiles without error* but generates a runtime binder exception at runtime. Removing the dynamic parameter to these methods causes a compiler error, as expected.

那么,为什么有一个动态参数允许代码被编译? 。ReSharper的不显示它是一个错误或者

So why does having a dynamic parameter allow the code to be compiled? ReSharper doesn't show it as an error either.

修改1: *在Visual Studio 2008

Edit 1: *in Visual Studio 2008

编辑2:添加密封,因为它可能是一个子类可以包含一个静态酒吧(。 ..)方法。即使它不是可能比实例方法之外的任何方法可以在运行时调用密封版本编译。

Edit 2: added sealed since it's possible that a subclass could contain a static Bar(...) method. Even the sealed version compiles when it's not possible that any method other than the instance method could be called at runtime.

推荐答案

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

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).

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

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.

这篇关于为什么C#编译器没有故障代码,其中一个静态方法调用一个实例方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆