Haxe中可变数量的参数 [英] Variable number of arguments in Haxe

查看:101
本文介绍了Haxe中可变数量的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在Haxe中执行类似操作的方法:

i'm looking for a way to do something like this in Haxe:

function foo(...args)  
{  
  for (arg in args)
  {
    ...
  }
}

这里有人可以帮助我吗?

Someone around here who can help me?

推荐答案

Haxe没有rest参数,主要是因为它们不是自然类型的,因此该语言应有助于输入具有最安全代码的语言.键入的代码可以由编译器检查和优化.更多的错误编译时间,更少的错误运行时间.

Haxe doesn't have rest arguments, mostly because those are untyped by nature, and the language should help going typed to have safest code. Typed code can be checked and also optimized by the compiler. More errors compile-time, less errors run-time.

取决于您要寻找的内容,仍然可以通过几种方式实现rest参数的相同结果;该函数只接收值还是对象?

Still the same result of rest arguments can be somehow achieved in a few ways, depending on what you are looking for; does the function only receive values or also objects?

最直接的方法是使用Any类型和Reflect:

The most straightforward way is using the Any type and Reflect:

function loop(props:Any) 
{
    for (prop in Reflect.fields(props))
    {
        trace(prop, Reflect.field(props, prop));
    }
}
// usage: 
loop({name: "Jerson", age: 31});

您只能使用带有值的数组,因此在使用它时还需要使用数组:

You can just use an array with values, therefore you also need to use an array when you use it:

static function loop(values:Array<Any>) 
{
    for (i in 0...values.length)
    {
         trace(i, values[i]);
    }
}
//usage:
loop(["Jerson", 31]);

如果您在实现中不喜欢此数组,则也可以使用此功能,我不建议使用,只是给出一个想法.

If you dislike this array in the implementation, you can also use this wonky function, which I wouldn't advice, but just to give an idea.

function loop<A,B,C,D,E,F>(?prop1:A, ?prop2:B, ?prop3:C, ?prop4:D, ?prop5:E, ?prop6:F) 
{
    var props:Array<Any> = [prop1,prop2,prop3,prop4,prop5,prop6];
    for (i in 0...props.length)
    {
         trace(i, props[i]);
    }
}
// usage: 
 loop3("Jerson", 31);

在此处尝试以下示例: https://try.haxe.org/#Be3b7

Try these examples here: https://try.haxe.org/#Be3b7

还有宏作为其余参数,如果您熟悉宏.请注意,这将在编译时进行跟踪,并且目前不会在输出源中生成跟踪.

There are also macros for rest arguments, which can be nice if you are familiar with macros. Note that this will trace while compiling and doesn't generate the trace in the output source at the moment.

import haxe.macro.Expr;

macro static function loop(e1:Expr, props:Array<Expr>)
{
    for (e in props) 
    {
        trace(e);
    }
    return macro null;
}
// Usage:
loop("foo", a, b, c);

最好的建议当然就是保持类型安全不要太动态,但这应该可以使您前进.

Best advice of course is just don't go dynamic much to keep type-safety, but this should keep you going.

这篇关于Haxe中可变数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆