简体   繁体   中英

How can I tell if an instance implements an interface in ActionScript 3.0

I am overriding the addItem() function of an array collection and I would like to detect if the added item implements a particular interface.

Previously I used the, is operator to detect the class type, but now that I am using an interface for classes I would rather test to see if the object implements the interface.

I expect I could just try and cast the object as the interface and see if it's not null . Is this the best way to do it?

I could also just create a new addFunction() that only accepts objects of the interface type.

You can still use is to test for an interface.

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768" creationComplete="application1_creationCompleteHandler(event)">
    <fx:Script>
        <![CDATA[
            import mx.events.FlexEvent;
            public var test:TestInterface = new TestInterface() //implements ITestInterface


            protected function application1_creationCompleteHandler(event:FlexEvent):void
            {
                trace(test is ITestInterface); //true
            }

        ]]>
    </fx:Script>
</s:Application>

添加到Joel的答案:如果您想了解有关类实现的接口(及其子类,父类等)的更多信息, AS3Commons库有一个ClassUtils类,它具有许多便捷方法。

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