2
我將一個庫從AS3移植到Haxe,我需要使一個方法接受可變數量的參數。目標是* .swc庫。Haxe - SWC中參數的可變數量
我的問題涉及this one但沒有建議的解決方案的輸出具有所需的簽名的方法:someMethod(...params)
相反,產生的方法是:someMethod(params:*=null)
這將在AS3項目使用未編譯庫和使用的代碼是我無法實現的。有沒有辦法做到這一點,也許宏?
我將一個庫從AS3移植到Haxe,我需要使一個方法接受可變數量的參數。目標是* .swc庫。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(", ");
}