以下是显示奇怪性的示例代码:(基于注释修复的代码)
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关键字?
查看C#规范,第7.6.5.2节指定扩展方法调用仅适用于以下格式的方法调用:
Run Code Online (Sandbox Code Playgroud)expr . identifier ( ) expr . identifier ( args ) expr . identifier < typeargs > ( ) expr . identifier < typeargs > ( args )
当它是一个独立的方法调用时,没有expr,所以它不寻找扩展方法.这是因为没有expr,它不知道扩展方法的第一个参数应该是什么.