如何将子类的实例强制转换为其超类?

时间:2013-11-24 15:02:48

标签: actionscript-3 types subclass superclass coercion

所以我有这个超类网格类,以及名为GrassTile1,GrassTile2等的网格类的子类......所有子类实例都存储在一个数组中。我怎么想把子类的实例转换为引用数组的超类?

private var backgroundGrid = []; //the array which the grids are stored in, in the main class.



public class Grid extends MovieClip
{

    protected var node :PathfindNode; //the variable I wish to access, from an instance of subclass.

    public function Grid(){
        node = new PathfindNode();
    }


}



public class GrassTile1 extends Grid { //every subclass of Grid will extends Grid


    public function GrassTile1() {
        // constructor code
    }
}

function getBackgroundGrid(i:int,j:int):Grid{ //in the main class
        return Grid(backgroundGrid[i][j]); // this line gives me an error 
    }

TypeError:错误#1034:类型强制失败:无法将GrassTile1 @ 2905d5f1转换为网格。

我已经尝试过访问backgroundGrid [i] [j] .node以及其他解决方法,我能想到并失败了。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试:

return backgroundGrid[i][j] as Grid;

就个人而言,Grid似乎是一个糟糕的类名。我认为Tile更有意义,因为GrassTile1不是网格,因为我在逻辑上理解网格。网格可能包含一组切片,因此将其用作切片的类名称听起来不合逻辑。

另外,实际调用getBackgroundGrid方法的行在哪里?你应该尝试在那里进行投射,而不是那种方法。我相信这样可以解决问题。

我无法验证抛出错误的行,所以我们假设它是return语句。但是,它可能在你调用getBackgroundGrid的另一边。

更新:我已经尝试使用你所描述的.fla并且它工作正常,我没有错误。这就是为什么我认为我们在这里遗漏了一些东西,也许这个类的定义没有被使用。您是否可以在构造函数中进行跟踪以验证您实际发生的情况?