2012-03-12 71 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

相關問題