检查 class 是否扩展了另一个 class

Check if class extends another class

明确地说,我想检查一个 class,而不是 class 的一个实例。

public function changeScene(newScene:Class):void 
{
  if(newScene isExtending Scene)
  //...
}

是Class类型的变量。

编辑:更多细节。 该函数的作用(简化):

public function changeScene(newScene:Class):void 
{
    currentScene.finish(); //Finish the scene that is about to change

    //Check if the new scene don't exist prior this point
    if (!scenes[newScene])  //Look in dictionary
        addScene(newScene); //Create if first time accessing it

    scenes[newScene].caller = currentScene["constructor"];
    currentScene = scenes[newScene];
    currentScene.start();
}

对我不起作用,因为我不会一直创建新实例,我大部分时间都在重复使用它们。这些实例使用 class 作为键存储在字典中。

这是我能想到的不实例化对象的唯一方法:

您使用 flash.utils.getQualifiedSuperclassName 获得 class 的超级 class。由于 returns 是一个字符串,因此您必须使用 flash.utils.getDefinitionByName 来获取实际的 class 引用。

因此您可以编写一个函数来遍历继承,直到找到匹配项或到达 Object(一切的基础)。

import flash.utils.getQualifiedSuperclassName;
import flash.utils.getQualifiedClassName;
import flash.utils.getDefinitionByName;

function extendsClass(cls:Class, base:Class):Boolean {
    while(cls != null && cls != Object){
        if(cls == base) return true;
        cls = getDefinitionByName(getQualifiedSuperclassName(cls)) as Class; //move on the next super class
    }
    return false;
}

trace(extendsClass(MovieClip,Sprite)); //true
trace(extendsClass(MovieClip,Stage)); //false

The other question doesn't work for me because I don't create new instances all the time, I reused them most of the time. The instances are stored in a dictionary using the class as the key.

我不敢苟同。

工厂模式封装了某个class对象的整个创建过程。这还包括限制实例化 class 的频率。 如果您只希望工厂生产一件物品,那是可能的。它将变成 Singleton.