在AS3中,我试图检查一个对象是一个实例,还是扩展一个特定的类。如果对象是if (object is ClassName)
的实例,则使用类似ClassName
的内容可以正常工作,但如果它是扩展 ClassName
的类的实例则不行。
伪代码示例:
class Foo {}
class Bar extends Foo {}
var object = new Bar();
if (object is Foo){ /* not executed */ }
if (object is Foo){ /* is executed */ }
我想要类似的东西:
class Foo {}
class Bar extends Foo {}
var object = new Bar();
if (object is Foo){ /* is executed */ }
任何想法?
答案 0 :(得分:5)
package {
import flash.display.Sprite;
public class Main extends Sprite {
public function Main() {
var bar:Bar=new Bar();
trace("bar is Bar",bar is Bar);//true
trace("bar is Foo:",bar is Foo);//true
trace("bar is IKingKong:",bar is IKingKong);//true
trace(describeType(bar));
//<type name="Main.as$0::Bar" base="Main.as$0::Foo" isDynamic="false" isFinal="false" isStatic="false">
//<extendsClass type="Main.as$0::Foo"/>
//<extendsClass type="Object"/>
//<implementsInterface type="Main.as$0::IKingKong"/>
//</type>
}
}
}
interface IKingKong{}
class Foo implements IKingKong{}
class Bar extends Foo{}
答案 1 :(得分:1)
你可以这样做:
class Foo {}
class Bar extends Foo {}
var object = new Bar();
if (object as Foo != null) { /* is executed */ }
答案 2 :(得分:0)
使用接口或抽象类,您应该可以执行此操作
var object:Foo = new Bar();
if (object is Foo){ /* is executed */ }
//or
var object:IFoo = new Bar();
if (object is IFoo){ /* is executed */ }
答案 3 :(得分:0)
package
{
import flash.display.Sprite;
import flash.utils.getQualifiedSuperclassName;
public class Test extends Sprite
{
public function Test()
{
trace(getQualifiedSuperclassName(this)); //returns "flash.display::Sprite"
}
}
}