AS3将一种类型转换为另一种类型

Bru*_*orn 12 flash actionscript-3

我有一个被调用的基类Room和一个被调用的子类Attic,另一个被调用Basement.

我有一个控制器类,它有一个名为CurrentLocationtype 的属性Room.我的想法是希望能够放入AtticBasement放入该属性并将其恢复,然后将其转换为任何类型.

因此,如果在控制器上内容属于类型Attic,我正在试图弄清楚如何显式地转换它.我以为我知道但它不起作用......这就是我认为的,借用Java:

var myAttic:Attic = (Attic) Controller.CurrentLocation;
Run Code Online (Sandbox Code Playgroud)

这给了我一个语法错误:

1086:语法错误:在实例之前期待分号.

那么你如何隐含地投射?或者你呢?我可以发誓我之前做过这样的事情.

Mar*_*rty 25

以下是在ActionScript 3中进行强制转换的选项:

  1. 使用as.

    var myAttic:Attic = Controller.CurrentLocation as Attic; // Assignment.
    (Controller.CurrentLocation as Attic).propertyOrMethod(); // In-line use.
    
    Run Code Online (Sandbox Code Playgroud)

    这将分配nullmyAttic,如果转换失败.

  2. 包裹Type().

    var myAttic:Attic = Attic(Controller.CurrentLocation); // Assignment.
    Attic(Controller.CurrentLocation).propertyOrMethod(); // In-line use.
    
    Run Code Online (Sandbox Code Playgroud)

    TypeError如果演员表失败,则抛出一个.

  • 为什么这是首选?这取决于.如果失败,那么`Class(bla)`会慢几个数量级.检查"null"总是更容易. (2认同)