ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
>[warning] **定义**:静态扩展 一个静态扩展允许伪装扩展存在的类型而不用修改它们的源码。在Haxe中这是通过声明一个静态方法,第一个参数是要扩展的类型,然后带入定义类到上下文中就可以使用。 >[warning] Definition: Static Extension A static extension allows pseudo-extending existing types without modifying their source. In Haxe this is achieved by declaring a static method with a first argument of the extending type and then bringing the defining class into context through using. 静态扩展是一个强大的工具,使得可以不用实际修改就对类型进行扩展。下面的示例展示用法: > Static extensions can be a powerful tool which allows augmenting types without actually changing them. The following example demonstrates the usage: ~~~ using Main.IntExtender; class IntExtender { static public function triple(i:Int) { return i * 3; } } class Main { static public function main() { trace(12.triple()); } } ~~~ 显然,Int并没有原生提供一个 triple 方法,然而这个程序编译并输出预期的 36 。这是因为调用 12.triple() 是转换到 IntExtender.triple(12) 。这有三个要求: > Clearly,Int does not natively provide a triple method,yet this program compiles and outputs 36 as expected. This is because the call to 12.triple() is transformed into IntExtender.triple(12). There are three requirements for this: 1. 字面的值12和第一个参数都是已知的Int类型 2. IntExtender类通过 using Main.IntExtender 带入到上下文 3. Int本身没有 triple字段(如果它有,那个字段会优先于静态扩展) > 1. Both the literal 12 and the first argument of triple are known to be of type Int. > 2. The class IntExtender is brought into context through using Main.IntExtender. > 3. Int does not havea triple field by itself (if it had,that field would take priority over the static extension). 静态扩展通常认为是语法糖,事实也是如此,但是值得注意的是,它们可以对代码可读性有一个戏剧性影响:替代嵌套的调用形式如f1(f2(f3(f4(x)))),使用链式调用形式如x.f4().f3().f2().f1() 。 > Static extensions are usually considered syntactic sugar and indeed they are, but it is worth noting that they can have a dramatic effect on code readability: Instead of nested calls in the form of f1(f2(f3(f4(x)))), chained calls in the form of x.f4().f3().f2().f1() can be used. 遵守前面讲述过的解析顺序(第3.7.3节),多个使用的表达式从底部到头部检查,而在每个模块的类型以及在每个类型中的字段从头至尾检查。使用一个模块(而不是一个模块中的特定类型,查看模块和路径(第3.7节))作为静态扩展会把所有它的类型带入上下文中。 > Following the rules previously described in Resolution Order(Section3.7.3),multiple using expressions are checked from bottom to top, with the types within each module as well as the fields within each type being checked from top to bottom. Using a module (as opposed to a specific type of a module, see Modules and Paths (Section 3.7)) as static extension brings all its types into context.