Haxe中的`using`关键字是什么?

时间:2015-06-19 08:30:10

标签: using haxe

我经常看到人们在他们的Haxe代码中使用关键字using。它似乎追随import陈述。

例如,我发现这是一段代码:

import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
using haxe.macro.Tools;
using Lambda;

它做什么以及如何运作?

1 个答案:

答案 0 :(得分:14)

"使用" Haxe的mixin功能也称为" static extension"。它是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;
    }
}
  

在此处运行此示例:http://try.haxe.org/#C96B7

更多Haxe文档:

相关问题