我经常看到人们using在他们的Haxe代码中使用关键字.它似乎追随了这些import陈述.
例如,我发现这是一个代码片段:
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
using haxe.macro.Tools;
using Lambda;
Run Code Online (Sandbox Code Playgroud)
它做什么以及如何工作?
Mar*_*nol 14
Haxe的"使用"mixin功能也称为" 静态扩展 ".这是Haxe的一个很好的语法糖特征; 它们可以对代码可读性产生积极影响.
静态扩展允许伪扩展现有类型而无需修改其源.在Haxe中,这是通过使用扩展类型的第一个参数声明一个静态方法,然后通过using关键字将定义类放入上下文中来实现的.
看看这个例子:
using Test.StringUtil;
class Test {
static public function main() {
// now possible with because of the `using`
trace("Haxe is great".getWordCount());
// otherwise you had to type
// trace(StringUtil.getWordCount("Haxe is great"));
}
}
class StringUtil {
public static inline function getWordCount(value:String) {
return value.split(" ").length;
}
}
Run Code Online (Sandbox Code Playgroud)
在此处运行此示例:http://try.haxe.org/#C96B7
更多Haxe文档: