开发者

Please tell me how to create an object if the name is stored in a variable

开发者 https://www.devze.com 2023-01-24 08:05 出处:网络
Please tell me how to create an object if the name is stored in a variable. var className:String 开发者_JAVA技巧= \'Config\';

Please tell me how to create an object if the name is stored in a variable.

var className:String 开发者_JAVA技巧= 'Config';
var MySprite:Sprite = new ???

class Config extends Sprite {
   ...
}


var configClass:Class = getDefinitionByName("Config") as Class;
var configInstance:Config = new configClass as Config;

EDIT: Aurel300 has a point. Statically typing to an exact class is senseless, simply because if you can explicitly code the exact type of what it is going to be, then you might as well create a class as per normal.

That being said, you will probably have somewhat of an idea of what the type could be, for example if you are dealing with audio you know it will inherit from Sound, or images you know it will inherit from Sprite. So in those cases best practise would be to statically type it as the lowest common base class. If it can be literally any class then there is no point in statically typing it at all, but I can not think of any useful reason why you would create classes that could be anything.

So if you are expecting the type to be Config or classes that inherit from Config then the code above is correct. Otherwise my guess is that you are expecting classes that extend Sprite (so you can add them to stage perhaps) so then you would change it to:

var configClass:Class = getDefinitionByName("Config") as Class;
var configInstance:Sprite= new configClass as Sprite;
0

精彩评论

暂无评论...
验证码 换一张
取 消