AS3:为什么数据类型会自动从 TextField 更改为 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 SimpleButton 类型的 var 由于未知原因更改为 DisplayObject,不允许我访问 .upState.textColor!。我发布这篇文章是因为它更有针对性,并且涉及更广泛问题的一个方面。
What's happening in this simple piece of AS3 code? Why does my object change from TextField to the more generic 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."
This question is simliar to AS3: global var of type SimpleButton changes to DisplayObject for unknown reason, won't let me access .upState.textColor!. I'm posting this because its more focused and deals with a single aspect of the broader issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您会看到编译时类型和运行时类型之间的差异。在此代码中:
您将对象传递给跟踪,跟踪将显示运行时存在的实际对象类型。
但是,在本例中:
您正在编写使用
upState
中的对象的代码。 upState 被定义为DisplayObject
并且所有DisplayObject
都没有textColor
属性,因此它必须给您一个错误。upState
允许实际包含DisplayObject
或DisplayObject
子类(如TextField
)的任何内容。您可以通过强制转换告诉编译器您确定它是一个
TextField
。还有另一种形式的转换,使用
as
关键字,它将返回按指定类型键入的对象,或null
。您想要使用此关键字来测试对象是否为某种类型,然后有条件地使用它(通过!= null
检查)。You're seeing the difference between compile time and run-time type. In this code:
You're passing the object to trace and trace is going to show the actual object type that exists at run-time.
However, in this case:
You're writing code that uses the object in
upState
. upState is defined asDisplayObject
and allDisplayObject
don't have atextColor
property, so it has to give you an error.upState
is allowed to actually contain anything that is aDisplayObject
or a subclass ofDisplayObject
like aTextField
.You can tell the compiler that you know for sure it's a
TextField
by casting it.There is another form of casting using the
as
keyword which will return the object, typed as specified, ornull
. You want to use this keyword to test if an object is a certain type and then conditionally use it (via a!= null
check).