Is it possible to declare AS3 vectors with a type reference?

Instead of this:

var v:Vector.<String> = new Vector.<String>(); 

Is there a way to do something like this?

 var myType:Class = String; var v:Vector.<myType> = new Vector.<myType>(); 

Obviously, this does not work as it is written, but I hope you get this idea.

+4
source share
3 answers

The short answer is to try grapefrukt and see.

However, I do not think this is possible at the bytecode level. The problem is related to the construction of generics (vectors). Basically the bytecode for instantiating Vector <> goes:

 GenericDefinitionType (Vector) + GenericParameter (int) -> GenericType Coerce (cast) GenericType as KnownGenericType (eg. "Vector.<int>") 

So the problem is not the creation, since the GenericParameter is just multi-named (which can be dynamic). The problem is forcing a known vector type (actually registered as "Vector. <int>", for example) since there is no known vector type.

See my post on how Vectors work in the bytecode to describe geeky.

+4
source

I found a way to create vectors dynamically. Instead of passing the type as a class, you pass the entire vector as a class, for example:

 public function createVector (vectorType:Object):Object { return new vectorType(); } var v:Vector.<String> = createVector(Vector.<String>); 

Or you can copy the vector as follows:

 public function getCopy (ofVector:Object):Object { var copy:Object = new ofVector.constructor; return copy; } 
0
source

This is not verified, but I do not understand why it should not work:

 import flash.display.Sprite; import flash.utils.getDefinitionByName; var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class; var v:Vector.<ClassReference> = new Vector.<ClassReference>(); 
-1
source

Source: https://habr.com/ru/post/1285792/


All Articles