AS3:为什么数据类型会自动从TextField更改为DisplayObject?

时间:2010-01-29 20:54:50

标签: actionscript-3 casting types displayobject

这个简单的AS3代码中发生了什么?为什么我的对象从TextField更改为更通用的DisplayObject?

public class Menu extends MovieClip
     {
      private var active_button:SimpleButton;

      public function Menu() 
      {
       active_button = SimpleButton( menu_list.getChildAt( 0 )); // ignore menu_list. it's just a collection of SimpleButtons
       trace( active_button.upState ); // [object TextField]
                // ** What's occuring here that makes active_button.upState no longer a TextField? **
       active_button.upState.textColor = 0x000000; // "1119: Access of possibly undefined property textColor through a reference with static type flash.display:DisplayObject." 

这个问题与AS3: global var of type SimpleButton changes to DisplayObject for unknown reason, won't let me access .upState.textColor!相似。我发布这个是因为它更专注于处理更广泛问题的一个方面。

1 个答案:

答案 0 :(得分:2)

您将看到编译时和运行时类型之间的区别。在这段代码中:

trace( active_button.upState ); // [object TextField]

您正在将对象传递给trace,trace将显示运行时存在的实际对象类型。

然而,在这种情况下:

active_button.upState.textColor = 0x000000;

您正在编写使用upState中对象的代码。 upState定义为DisplayObject,所有DisplayObject都没有textColor属性,因此必须给您一个错误。允许upState实际包含DisplayObject的任何内容或DisplayObject的子类TextField

您可以通过投射来告诉编译器您确定它是TextField

TextField(active_button.upState).textColor = 0x000000;

还有另一种使用as关键字的转换形式,该关键字将返回对象,按指定键入或null。您希望使用此关键字来测试某个对象是否属于某种类型,然后有条件地使用它(通过!= null检查)。

var textField:TextField = active_button.upState as TextField;
if (textField != null) {
    textField.textColor = 0;
}