一个简单的问题投对象...如何从一个数组
我有一个抽象类,细胞和两个类BorderCell和BoardCell,从细胞类继承。然后我有一个Cell []类型的Cells数组,其中包含BorderCell和BoardCell类型的对象。
abstract class Cell
{
}
class BorderCell : Cell
{
public void Method1(){};
}
class BoardCell: Cell
{
public void Method2(){};
}
...
Cell[] Cells = new Cell[x];
for (int i = 0; i < x; i++){
Cells[i] = new BorderCell();
// or
Cells[i] = new BoardCell();
}
现在我想将电池转换为BorderCell和运行其方法1,像这样:
(Border)Cells[i].Method1();
但是,这是不行的,我必须使用:
BorderCell borderCell = (BorderCell)Cells[i];
borderCell.Method1();
这是唯一(和正确的方式)做到这一点)?
我会在这里回顾一下你的设计 - 不得不抛弃到派生类是一种糟糕的设计气味 - 如果你将它们保存在同一个集合中作为基类型,我期望它们是真正的多态(Liskov原理)。 – 2010-06-30 09:32:17
Herbie博士:我很乐意提供建议,查看此主题:http://stackoverflow.com/questions/3140281/what-data-structure-to-use-in-my-example – sventevit 2010-06-30 09:47:54