简体   繁体   中英

How to check sub class type in super class in ActionScript3

I want to get sub class type in super class. I tried

if(this is SubClass1)

in the super class but failed.

Your code works :

package{
    import flash.display.Sprite;

    public class TestSuperClass extends Sprite{
        public function TestSuperClass(){
            super();
            trace((new SuperClass).isSubclass); // Output : false
            trace((new Extended).isSubclass); // Output : true
        }
    }
}

internal class SuperClass
{
    public function get isSubclass() : Boolean{
        return this is Extended;
    }
}

internal class Extended extends SuperClass {}

You can do it dynamically (that's ugly, not performance friendly, but it does the job) :

package{
    import flash.display.Sprite;

    public class TestSuperClass extends Sprite{
        public function TestSuperClass(){
            super();

            trace((new SuperClass).isSubclass); // Output : false
            trace((new SuperClass).superClass); // Output : Object
            trace((new Extended).isSubclass); // Output : true
            trace((new Extended).superClass); // Output : SuperClass
        }
    }
}
import flash.utils.describeType;

internal class SuperClass
{
    public function get isSubclass() : Boolean{
        return describeType(this).@base.toString() != "Object";
    }

    public function get superClass() : String
    {
        return describeType(this).@base.toString().split("::").pop();
    }
}

internal class Extended extends SuperClass {}

The super class doesn't know about his sub classes and shouldn't know. A subclass extends his superclass so should and knows about his super class.

What you are trying to achieve is not possible. There should be an other (better) way to solve for your problem/architecture.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM