Dynamically Casting In ActionScript

2019-08-19 13:32发布

问题:

Is there a way to cast dynamically in Actionscript? What I want to accomplish is illustrated by the following code:

        var Val:*;
        var S:String=SomeTextEdit.text;
        switch (DesiredTypeTextEdit.text) {
          case 'int':Val=int(S);break; 
          case 'uint':Val=uint(S);break; 
          case 'String':Val=String(S);break; 
          case 'Number':Val=Number(S);break; 
          ...
        }
        SomeDisplayObject[SomePropertyNameTextEdit.text]=Val;

I am looking for something LIKE the following PSEUDOCODE:

SomeDisplayObject[SomePropertyName]=eval(DesiredType)(SomeTextEdit.text);

Yes, I already realize that "eval" is not on the table, nor is that how one would use it.

What's the RIGHT way?

回答1:

You might be looking for something like this:

http://benrimbey.wordpress.com/2009/06/20/reflection-based-json-validation-with-vo-structs/

Check the "mapToFlexObjects" function. He's basically reading from text and assigning classes at runtime.



回答2:

You'll have to play the try-catch game, but googling some of these flash.utils would hopefully be a means to your end:

getDefinitionByName(getQualifiedClassName(variable))

You'll probably have to import all of the different 'types' you intend on using into the project somewhere, but this should get you started.



回答3:

Not too sure on exactly what you after (your example is a little confusing), but I will try and answer.

You can type-cast a variable only when you create a variable. You can do one of the following to change the type of a variable, but you must create a new variable of the new type.

var foo:Number = 230;
var foo2:int = foo as int;

or

var foo:Number = 230;
var foo2:int = int(foo);

If you use the asterisks (*) as your variable type, then what ever you set the variable to, it will become that type. Try this as a test:

var foo:* = new Sprite();
trace(foo); // Traces: "[object Sprite]"

This is somewhat bad practice, and bad software design. But sometimes you gotta do what you gotta do! How bad is dynamic casting?