我正在将一个库从 AS3 移植到 Haxe,并且我需要创建一个接受可变数量参数的方法。目标是一个 *.swc 库。
我的问题涉及this one但建议的解决方案都没有输出具有所需签名的方法:someMethod(...params)
相反,生成的方法是:someMethod(params:*=null)
这不会在使用该库的 AS3 项目中进行编译,并且所使用的代码超出了我的能力范围。有没有办法做到这一点,也许是宏?
最佳答案
嗯,这是一个很好的问题。而且,事实证明有一种方法可以做到这一点!
基本上, __arguments__
是Flash目标上的特殊标识符,主要用于访问特殊的局部变量 arguments
。但它也可以用在方法签名中,在这种情况下,它会更改 test(args: *)
的输出。至test(...__arguments__)
.
一个简单的例子(live on Try Haxe):
class Test {
static function test(__arguments__:Array<Int>)
{
return 'arguments were: ${__arguments__.join(", ")}';
}
static function main():Void
{
// the haxe typed way
trace(test([1]));
trace(test([1,2]));
trace(test([1,2,3]));
// using varargs within haxe code as well
// actually, just `var testm:Dynamic = test` would have worked, but let's not add more hacks here
var testm = Reflect.makeVarArgs(cast test); // cast needed because Array<Int> != Array<Dynamic>
trace(testm([1]));
trace(testm([1,2]));
trace(testm([1,2,3]));
}
}
最重要的是,这会生成以下内容:
static protected function test(...__arguments__) : String {
return "arguments were: " + __arguments__.join(", ");
}
关于actionscript-3 - Haxe - SWC 中参数数量可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46565083/