简体   繁体   English

在Dart中调用带有参数数组的函数

[英]Calling a function with an array of parameters in Dart

I'm trying to call a function in dart with a set of parameters that is provided in an array. 我正在尝试使用数组中提供的一组参数调用dart中的函数。 I want to be able to pass the parameters to the function without knowing how many parameters there will be. 我希望能够将参数传递给函数,而不知道将有多少参数。

Ex: 例如:

someFunc(var a, var b, var c) {...}
paramArray = [1,2,3];

callFunction(var func, var params) {
  //Here is a sloppy workaround to what I want the functionality to be
  switch(params.length) {
  case 0:
      func()
      break;
    case 1: 
      func(params[0])
      break;
    case 2: 
      func(params[0], params[1])
      break;
    ...
  }
}

callFunction(someFunc, paramArray);

Does there exist a cleaner way to do this in dart without changing the signature of someFunc? 是否有更简洁的方法在dart中执行此操作而不更改someFunc的签名?

The Function.apply method does precisely what you want. Function.apply方法正是您想要的。 You can do Function.apply(func, params) and it will call func if the parameters match (and throw if they don't). 您可以执行Function.apply(func, params) ,如果参数匹配则调用func如果参数不匹配则抛出)。

Not to my knowledge. 据我所知。 At this point, Dart doesn't support varargs . 此时,Dart不支持varargs For now, just take an Iterable as a parameter instead. 现在,只需将Iterable作为参数。

I posted a similar question not so long ago : Packing/Unpacking arguments in Dart 我不久前发布了一个类似的问题: 在Dart中打包/解包参数

Currently not supported but the dart team is aware of this feature. 目前不支持,但是飞镖队已经知道这个功能。 Not their priority though. 不过他们的优先权。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM