我可以创建AS3只知道他的名字一类的实例?只知道、他的名字、实例

2023-09-08 12:03:02 作者:你怎么这么可爱啊

我可以建立从AS3类的一个实例,只知道它的名字?我的意思是字符串重新presentation,如 FlagFrance

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

推荐答案

动态的名字创建类的实例。要做到这一点下面的code,可以用:

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."

我们需要指定返回值作为类以上code?这是因为getDefinitionByName也可以返回一个函数(如 flash.utils.getTimer - 一个包级别的功能,是不是在任何类)。由于返回类型可以是一个函数或一类的Flex团队指定的返回类型为对象,并有望进行类型转换是必要的。

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.

以上code密切模仿在文档中给出​​的例子,但在一个方式,它是一个坏榜样,因为一切都将正常工作的 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.

原因错误是,你必须有一个引用类在code - 如:你需要创建一个变量,并指定它的类型,像这样:

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;

如果没有这样做,你的类将不再对瑞士法郎在编译时编译。编译器仅包括实际使用(而不仅仅是进口)班。它这样做,以便优化。瑞士法郎的大小。所以需要声明一个变量应该没有真正被视为疏忽或错误,但它确实感觉hackish的声明,你不直接使用一个变量。

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.