我可以只知道他的名字就从 AS3 创建一个类的实例吗? [英] Can I create an instance of a class from AS3 just knowing his name?

查看:29
本文介绍了我可以只知道他的名字就从 AS3 创建一个类的实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以仅知道名称就从 AS3 创建类的实例吗?我的意思是字符串表示,比如 FlagFrance

Can I create an instance of a class from AS3 just knowing it's name? I mean string representation, like FlagFrance

推荐答案

按名称动态创建类的实例.为此,可以使用以下代码:

Create instances of classes dynamically by name. To do this following code can be used:

 //cc() is called upon creationComplete
   private var forCompiler:FlagFrance; //REQUIRED! (but otherwise not used)

   private function cc():void
   {
      var obj:Object = createInstance("flash.display.Sprite");
   }

   public function createInstance(className:String):Object
   {
      var myClass:Class = getDefinitionByName(className) as Class;
      var instance:Object = new myClass();
      return instance;
   }

getDefinitionByName 的文档说:

The docs for getDefinitionByName say:

"Returns a reference to the class object of the class specified by the name parameter."

上面的代码我们需要将返回值指定为Class吗?这是因为 getDefinitionByName 也可以返回一个函数(例如 flash.utils.getTimer - 一个不在任何类中的包级函数).由于返回类型可以是函数或类,因此 Flex 团队将返回类型指定为 Object,您需要根据需要执行强制转换.

The above code we needed to specify the return value as a Class? This is because getDefinitionByName can also return a Function (e.g. flash.utils.getTimer - a package level function that isn't in any class). As the return type can be either a Function or a Class the Flex team specified the return type to be Object and you are expected to perform a cast as necessary.

上面的代码与文档中给出的示例非常相似,但在某种程度上它是一个糟糕的示例,因为对于 flash.display.Sprite,一切都可以正常工作,但请尝试做同样的事情使用自定义类,您可能最终会遇到以下错误:

The above code closely mimics the example given in the docs, but in one way it is a bad example because everything will work fine for flash.display.Sprite, but try to do the same thing with a custom class and you will probably end up with the following error:

ReferenceError: Error #1065: Variable [name of your class] is not defined.

错误的原因是您必须在代码中引用您的类 - 例如您需要创建一个变量并指定它的类型,如下所示:

The reason for the error is that you must have a reference to your class in your code - e.g. you need to create a variable and specify it's type like so:

private var forCompiler:SomeClass;

如果不这样做,您的类将不会在编译时编译为 .swf.编译器只包含实际使用的类(而不仅仅是导入的).这样做是为了优化 .swf 的大小.因此,声明一个变量的需要不应真正被视为疏忽或错误,尽管声明一个您不直接使用的变量确实让人感觉有些不妥.

Without doing this your class will not be compiled in to the .swf at compile time. The compiler only includes classes which are actually used (and not just imported). It does so in order to optimise the size of the .swf. So the need to declare a variable should not really be considered an oversight or bug, although it does feel hackish to declare a variable that you don't directly use.

这篇关于我可以只知道他的名字就从 AS3 创建一个类的实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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