.NET Framework 要求每个方法都存在于程序集中的类中。一种语言可以允许在没有明确指定的封闭类的情况下声明方法或字段,将所有这些方法放在汇编中Fnord
的一个名为的类中Fnord_TopLevelDefault
,然后Fnord_TopLevelDefault
在执行方法查找时搜索所有汇编的类;但是,必须扩展 CLS 规范才能使此功能在混合语言项目中顺利运行。与扩展方法一样,如果 CLS 不承认,这种行为可能是符合 CLS 的,因为不使用这种特性的语言中的代码可以通过拼写Foo
在汇编中使用“自由浮动”方法,但是会有点难看。Fnord
Fnord_TopLevelDefault.Foo
A more interesting question is the extent to which allowing an extension method Foo
to be invoked from an arbitrary class without requiring a clearly visible reference to that class is less evil than would be allowing a non-extension static methods to be likewise invoked. I don't think Math.Sqrt(x)
is really more readable than Sqrt
; even if one didn't want to import Math
everywhere, being able to do so at least locally could in some cases improve code legibility considerably.