在Dart中创建具有可变数目的参数或参数的函数 [英] Creating function with variable number of arguments or parameters in Dart

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

问题描述

我正在寻找一种方法来创建一个具有可变数量的参数或Dart中的参数的函数。我知道我可以创建一个数组参数,但我宁愿不这样做,因为我在一个库,其中语法简洁是重要的。

I am looking for a way to create a function with a variable number of arguments or parameters in Dart. I know I could create an array parameter instead, but I would prefer to not do that because I'm working on a library where syntactic brevity is important.

例如,在纯JavaScript中,我们可以这样做(从这里借用):

For example, in plain JavaScript, we could do something like this (borrowed from here):

function superHeroes() {
  for (var i = 0; i < arguments.length; i++) {
    console.log("There's no stopping " + arguments[i]);
  }
}

superHeroes('UberMan', 'Exceptional Woman', 'The Hunk');

但是,在dart中,该代码不会运行。有没有办法在dart做同样的事情?

However, in dart, that code will not run. Is there a way to do the same thing in dart? If not, is this something that is on the roadmap?

推荐答案

现在不能这样做。

我真的不知道 varargs 是否会回来 - 他们以前在那里,但已删除

I don't really know if varargs will come back - they were there some times ago but have been removed.

可以使用仿真功能模拟 varargs 。请参阅以下代码段。

However it is possible to emulate varargs with Emulating functions. See the below code snippet.

typedef dynamic OnCall(List);

class VarargsFunction extends Function {
  OnCall _onCall;

  VarargsFunction(this._onCall);

  call() => _onCall([]);

  noSuchMethod(Invocation invocation) {
    final arguments = invocation.positionalArguments;
    return _onCall(arguments);
  }
}

main() {
  final superHeroes = new VarargsFunction((arguments) {
    for (final superHero in arguments) {
      print("There's no stopping ${superHero}");
    }
  });
  superHeroes('UberMan', 'Exceptional Woman', 'The Hunk');
}

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

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