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

What is the `using` keyword in Haxe?

我经常看到人们在他们的 Haxe 代码中使用关键字 using。它似乎遵循 import 语句。

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

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

它有什么作用以及它是如何工作的?

Haxe 的 "using" mixin 特性也被称为“static extension”。这是 Haxe 的一个很棒的语法糖功能;它们可以对代码的可读性产生积极影响。

静态扩展允许在不修改其源的情况下伪扩展现有类型。在 Haxe 中,这是通过使用 扩展类型 的第一个参数声明静态方法,然后通过 using 关键字将定义 class 引入上下文来实现的。

看看这个例子:

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 this example here: http://try.haxe.org/#C96B7

Haxe 文档中的更多内容: