如果构造函数将其参数作为vararg(...),则似乎无法创建只将该vararg传递给超类的子类。
对于正常功能的相同情况,有一个相关问题需要修复: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
除了实际将参数处理移动到子类或将其转移到单独的初始化方法之外,有没有人知道如何使超级调用正确?
答案 0 :(得分:2)
遗憾的是,无法使用... args
调用超级构造函数。如果删除super()
调用,编译器将调用它(不带参数)。构造函数也无法访问arguments
。
如果您可以更改方法签名,则修改参数以接受Array
而不是... args
。否则,正如您所提到的,您可以将其移动到初始化方法中。
答案 1 :(得分:0)
你可以使用这样的声明:
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;
}
}