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

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

问题描述

以下代码具有一个静态方法, Foo(),调用一个实例方法 Bar()

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.

在Visual Studio 2008中修改1: *

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

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

另外:所以我认为动态原始问题的例子是,为了保持一致,当类型是动态的时候,我们也首先找到最好的重载(仅检查参数号和参数类型等等,而不是静态与非静态),只有然后检查静态。但是这意味着静态检查必须等到运行时。因此观察到的行为。

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.

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

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