AS3: cast or “as”?

前端 未结 8 1698
天命终不由人
天命终不由人 2020-11-30 10:25

Is there any difference of use, efficiency or background technique between

var mc:MovieClip = MovieClip(getChildByName(\"mc\"));

and

<
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 11:00

    (cast) and "as" are two completely different things. While 'as' simply tells the compiler to interpret an object as if it were of the given type (which only works on same or subclasses or numeric/string conversions) , the (cast) tries to use a static conversion function of the target class. Which may fail (throwing an error) or return a new instance of the target class (no longer the same object). This explains not only the speed differences but also the behavior on the Error event, as described by Alejandro P.S.

    The implications are clear: 'as' is to be used if the class of an object is known to the coder but not to the compiler (because obfuscated by an interface that only names a superclass or '*'). An 'is' check before or a null check after (faster) is recommended if the assumed type (or a type compatible to auto-coercion) cannot be 100% assured.

    (cast) is to be used if there has to be an actual conversion of an object into another class (if possible at all).

提交回复
热议问题