代码之家  ›  专栏  ›  技术社区  ›  Simon Groenewolt

从带有varargs的actionscript构造函数调用super()。

  •  2
  • Simon Groenewolt  · 技术社区  · 15 年前

    如果一个构造函数将其参数作为vararg(…)接受,那么似乎不可能创建一个子类,该子类只将该vararg传递给超类。

    对于正常功能的相同情况,有一个与fix相关的问题: Wrapping a Vararg Method in ActionScipt 但我不能用超级电话。

    基类:

    public class Bla
    {
        public function Bla(...rest)
        {
            trace(rest[0]); // trace the first parameter
        }
    
    }
    

    子类:

    public class Blie extends Bla
    {
        public function Blie(...rest)
        {
            // this is not working, it will 
            // pass an array containing all 
            // parameters as the first parameters
            super(rest); 
        }
    
    }
    

    如果我现在打电话

            var b1 = new Bla('d', 'e');
            var b2 = new Blie('a', 'b', 'c');
    

    我得到输出

    d
    a,b,c
    

    我想把它打印出来:

    d
    a
    

    除了将参数的处理实际移动到子类或将其转移到单独的初始值设定项方法之外,还有人知道如何正确地进行超级调用吗?

    2 回复  |  直到 12 年前
        1
  •  2
  •   Richard Szalay    15 年前

    不幸的是,没有办法用 ... args . 如果你移除 super() 调用,编译器将调用它(不带参数)。 arguments 也无法从构造函数访问。

    如果可以更改方法签名,则可以修改参数以接受 Array 而不是 …阿尔茨海默病 . 否则,正如您所提到的,您可以将它移到初始值设定项方法中。

        2
  •  0
  •   whitered    12 年前

    您可以使用这样的语句:

    override public function doSomething(arg1:Object, ...args):void {
      switch(args.length) {
        case 0: super.doSomething(arg1); return;
        case 1: super.doSomething(arg1, args[0]); return;
        case 2: super.doSomething(arg1, args[0], args[1]); return;
      }
    }