AS3:投射到矢量

时间:2012-10-15 06:31:47

标签: actionscript-3 vector

我正在尝试创建一个来自未知类的向量,但它失败了,有关如何做的任何想法?

这是我试过的:

var vector:Vector = new Vector(); // throw exception

function base():void{
var vector:Vector.<String> = createVector(String);// throw classCastException
}

function createVector(cls:Class):*{
     var array:Array = new Array();
     for(var i:int = 0; i < 10; i++){
         var element:cls = new cls();
          array.push(element);
     }

     return Vector(array);
}

2 个答案:

答案 0 :(得分:2)

Vector期待参数类型,因此您不能按照自己的意愿执行此操作,但使用getQualifiedClassName获取类信息可以构造一个字符串,使您可以调用Vector。构造函数使用getDefinitionByName

实施例

// get class parameter name
var className:String=getQualifiedClassName(String);

// get the Vector class object for the given class
var o:Object=getDefinitionByName("__AS3__.vec::Vector<"+className+">");

// call the constructor
var v:*=o.prototype.constructor(["hello", "world"]);

所以你的功能可以写成:

    public function createVector(cls:Class):*{
        var cn:String = getQualifiedClassName(cls);
        var o:Object = getDefinitionByName("__AS3__.vec::Vector.<"+cn+">");
        var array:Array = [];
        for(var i:int = 0; i < 10; i++){
            var element:* = new cls();
            array.push(element);
        }
        return o.prototype.constructor(array);
    }

在wonderfl的实例: http://wonderfl.net/c/pkjs

答案 1 :(得分:1)

根据@Patrick回答,我找到了一个有效的解决方案。

检查出来:

function createVector(cls:Class):*{
        var className:String = getQualifiedClassName(cls);
        var vectorClass:Class = getDefinitionByName("__AS3__.vec::Vector.<"+className+">") as Class;

        var vector:* = new vectorClass(10);        
        for(var i:int = 0; i < 10; i++){
            var element:MyClass = new cls(); // may be Object or Object extends cls
            vector[i] = element;
        }

        return vector;
    }