为什么超类的扩展方法需要这个?

Lee*_*aas 2 c#

以下是显示奇怪性的示例代码:(基于注释修复的代码)

public class C{}
public static class E {
  public static void Foo(this C o) { }
 }
class D:C {
  void test() {
//  Foo(); // will not compile
    this.Foo(); // compile ok
  }
}
Run Code Online (Sandbox Code Playgroud)

在自然场景中,C类将是一个我无法访问其源代码的类

任何人都知道为什么这个奇怪的要求使用this关键字?

the*_*oop 8

查看C#规范,第7.6.5.2节指定扩展方法调用仅适用于以下格式的方法调用:

expr . identifier ( )  
expr . identifier ( args )  
expr . identifier < typeargs > ( )  
expr . identifier < typeargs > ( args )  
Run Code Online (Sandbox Code Playgroud)

当它是一个独立的方法调用时,没有expr,所以它不寻找扩展方法.这是因为没有expr,它不知道扩展方法的第一个参数应该是什么.

  • 我怀疑它是由于相同的语法能够在包含类上调用静态方法 - 对于一个,有一个`this`,而另一个,没有,但两者看起来都一样.前面的`expr`将它限制为实例方法. (2认同)