从 ActionScript 3 中的字符串实例化一个类 [英] Instantiate a class from a string in ActionScript 3

查看:29
本文介绍了从 ActionScript 3 中的字符串实例化一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,它在运行时包含我想要实例化的类的名称.我该怎么做?

I've got a string which, in run-time, contains the name of a class that I want to instantiate. How would I do that?

我阅读了使用 flash.utils.getDefinitionByName() 的建议:

I read suggestions to use flash.utils.getDefinitionByName():

var myClass:Class = getDefinitionByName("package.className") as Class;
var myInstance:* = new myClass();

但是,这给了我以下错误:

However, that gives me the following error:

[Fault] 异常,信息=ReferenceError:错误 #1065:未定义变量类名.

[Fault] exception, information=ReferenceError: Error #1065: Variable className is not defined.

推荐答案

我想出的最简单的方法是在项目的任何位置简单地写出类名,用分号分隔.

The easiest method I've come up with is to simply write the classnames out, separated by semicolons, anywhere in your project.

例如我在其中创建了一个 Assets.as 文件:

e.g. I create an Assets.as file with this in it:

package {   

public class Assets {       

    // To avoid errors from the compiler when calling getDefinitionByName
    // just list all of the classes that are not otherwise referenced in code:
    Balloon;
    Cloud;
    FlyingHorse;
    FlyingPig;
    UFO;
    Zeppelin;       
}
}

完整的代码示例/教程在这里:http://producerism.com/blog/flashpunk-dame-and-lua-tutorial-part-6/

Full code example/tutorial on this is here: http://producerism.com/blog/flashpunk-dame-and-lua-tutorial-part-6/

这篇关于从 ActionScript 3 中的字符串实例化一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆