【问题标题】:Get a collection of arguments passed to a Dart function/constructor call获取传递给 Dart 函数/构造函数调用的参数集合
【发布时间】:2015-08-10 12:11:36
【问题描述】:

我实际上是在寻找 JavaScript arguments 功能,但在 Dart 中。

这在 Dart 中可行吗?

【问题讨论】:

    标签: dart


    【解决方案1】:

    你必须和noSuchMethod一起玩才能做到这一点(见Creating function with variable number of arguments or parameters in Dart

    在班级级别:

    class A {
      noSuchMethod(Invocation i) {
        if (i.isMethod && i.memberName == #myMethod){
          print(i.positionalArguments);
        }
      }
    }
    
    main() {
      var a = new A();
      a.myMethod(1, 2, 3);  // no completion and a warning
    }
    

    或在字段级别:

    typedef dynamic OnCall(List l);
    
    class VarargsFunction extends Function {
      OnCall _onCall;
    
      VarargsFunction(this._onCall);
    
      call() => _onCall([]);
    
      noSuchMethod(Invocation invocation) {
        final arguments = invocation.positionalArguments;
        return _onCall(arguments);
      }
    }
    
    class A {
      final myMethod = new VarargsFunction((arguments) => print(arguments));
    }
    
    main() {
      var a = new A();
      a.myMethod(1, 2, 3);
    }
    

    第二个选项允许为myMethod 完成代码并避免警告。

    【讨论】:

    • 这两种方法都适用于构造函数吗?
    • 不,但您可以使用静态方法最终返回一个实例。
    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多