AS3 将一种类型转换为另一种类型 [英] AS3 Casting one type to another
问题描述
我有一个名为 Room
的基类和一个名为 Attic
的子类,以及另一个名为 Basement
的子类.
I have a base class called Room
and a subclass called Attic
, and another called Basement
.
我有一个控制器类,它有一个名为 CurrentLocation
的属性,它是 Room
类型.这个想法是我希望能够将 Attic
或 Basement
放在该属性中并将其取回,然后将其转换为任何类型.
I have a controller class that has an attribute called CurrentLocation
which is type Room
. The idea is I want to be able to put Attic
or Basement
in that property and get it back, then cast that to whatever type it is.
因此,如果控制器上的内容是 Attic
类型,我正在尝试弄清楚如何显式转换它.我以为我知道,但它不起作用......这是我认为的,从 Java 借来的:
So if on the controller the content is of type Attic
, I'm trying to figure out how to explicitly cast it. I thought I knew but its not working... Here's what I thought it would be, borrowing from Java:
var myAttic:Attic = (Attic) Controller.CurrentLocation;
这给了我一个语法错误:
This gives me a syntax error:
1086:语法错误:在实例之前需要分号.
1086: Syntax error: expecting semicolon before instance.
那么你如何隐式转换?或者你可以吗?我可以发誓我以前在 as3 中做过这件事.
So how do you cast implicitly? Or can you? I could swear I've done this before as as3.
推荐答案
以下是您在 ActionScript 3 中投射的选项:
Here are your options for casting in ActionScript 3:
使用
as代码>
.
var myAttic:Attic = Controller.CurrentLocation as Attic; // Assignment.
(Controller.CurrentLocation as Attic).propertyOrMethod(); // In-line use.
如果转换失败,这会将 null
分配给 myAttic
.
This will assign null
to myAttic
if the cast fails.
包裹在 Type()
中.
var myAttic:Attic = Attic(Controller.CurrentLocation); // Assignment.
Attic(Controller.CurrentLocation).propertyOrMethod(); // In-line use.
这会引发 TypeError
如果转换失败.
This throws a TypeError
if the cast fails.
这篇关于AS3 将一种类型转换为另一种类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!