2015-05-22 71 views
1

要清楚,我想檢查一個類,而不是該類的一個實例。檢查類是否擴展了另一個類

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(); 
} 

This question不適合我,因爲我沒有創建新實例的時候,我重用他們的大部分時間。這些實例以類爲關鍵字存儲在字典中。

+0

可能重複:http://stackoverflow.com/questions/28205385/when-using-the-class-datatype-how-can-i-specify-the-type-so-i-only-accept-sub/28220451#28220451 – null

回答

1

這是我能想到的這樣做沒有實例化對象的唯一方法:

您使用flash.utils.getQualifiedSuperclassName的得到超級類的類。由於該函數返回一個字符串,因此必須使用flash.utils.getDefinitionByName來獲取實際的類參考。

所以,你可以寫走到繼承,直到它找到一個匹配,或達到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 
+0

但要清楚,首先實例化並檢查實例會更好,併爲您提供編譯時檢查。如果你在if(newScene isExtending Scene)之後顯示你做了什麼'可以給出更加定製的解決方案 - 當這回答你的問題時,它不一定是製作你的應用程序的最佳方式。 – BadFeelingAboutThis

+0

這適用於我,謝謝。 – Deban

0

其他問題不適合我,因爲我不創造新的 情況下,所有的時間,我重用他們的大部分時間。實例 存儲在使用該類作爲鍵的字典中。

我不敢苟同。

工廠模式封裝了某個類的對象的整個創建。這還包括限制類實例化的頻率。 如果你只想要工廠生產一個對象,那是可能的。它會變成Singleton。的

+0

PO只是使用複雜而弱的方式來複制一個非常簡單和易於使用的Singleton模式。 – BotMaster

相關問題