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

查看:43
本文介绍了在 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 中,我们可以做这样的事情(从 here):

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 中,该代码不会运行.有没有办法在飞镖中做同样的事情?如果没有,这是路线图上的内容吗?

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 OnCall = dynamic Function(List arguments);

class VarargsFunction {
  VarargsFunction(this._onCall);
  
  final OnCall _onCall;

  noSuchMethod(Invocation invocation) {
    if (!invocation.isMethod || invocation.namedArguments.isNotEmpty)
      super.noSuchMethod(invocation);
    final arguments = invocation.positionalArguments;
    return _onCall(arguments);
  }
}

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

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

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