2012-03-12 75 views
12

我有一个称为Room的基类和一个名为Attic的子类,另一个称为BasementAS3将一种类型转换为另一种

我有一个控制器类有一个属性CurrentLocation这是Room类型。我的想法是,我希望能够将AtticBasement放入该属性中并将其取回,然后将其转换为任何类型。

因此,如果在控制器上的内容是类型Attic,我想弄清楚如何明确地施放它。我想我知道,但它不工作......这就是我认为这将是,从Java借款:

var myAttic:Attic = (Attic) Controller.CurrentLocation; 

这给了我一个语法错误:

1086: Syntax error: expecting semicolon before instance.

所以你投隐含怎么办?或者你能吗?我可以发誓我之前做过as3。

回答

25

这里是您在ActionScript 3铸造选项:

  1. 使用as

    var myAttic:Attic = Controller.CurrentLocation as Attic; // Assignment. 
    (Controller.CurrentLocation as Attic).propertyOrMethod(); // In-line use. 
    

    如果转换失败这将分配给nullmyAttic

  2. 裹在Type()

    var myAttic:Attic = Attic(Controller.CurrentLocation); // Assignment. 
    Attic(Controller.CurrentLocation).propertyOrMethod(); // In-line use. 
    

    如果转换失败,则抛出TypeError

+2

为什么这首选?这取决于。如果它失败,'Class(bla)'也是慢几个数量级。检查'null'总是比较容易。 – 2012-03-12 07:35:29

+0

@Marty华莱士如此告诉我们如何“喜欢”包装在数组,XML或对象? – 2012-03-12 08:49:06

+0

@Marty Wallace想象我们有数组或XML或对象类型而不是阁楼。这会影响你的答案吗? – 2012-03-12 08:54:12

相关问题