[英]How should I call a base class constructor with a class derived from a generic base class?
我有一个包含Cell
的通用 class Grid
。 我的计划是为Grid
(TriangleGrid、SquareGrid、HexGrid)和Cell
(TriangleCell、SquareCell、HexCell)创建几个派生类。 每个Grid
都有一个GetAdjacentCells
方法。
abstract public class Grid<T> where T:Cell {
protected T[,] cells_;
abstract public List<T> GetAdjacentCells(T cell);
}
abstract public class Cell {
protected Grid<Cell> grid_;
public Cell(Grid<Cell> grid, int x, int y) {
grid_ = grid;
}
}
HexGrid
派生类:
public class HexGrid : Grid<HexCell> {}
和
public class HexCell : Cell {
public HexCell(HexGrid grid, int x, int y)
: base(grid, x, y) { // compilation error here!
}
}
每个Cell
都有一个对其Grid
的引用,该引用通过Cell
构造函数传入。 我面临的问题是HexCell
构造函数调用base
时出现错误,它说:
Error CS1503 Argument 1: cannot convert from 'HexGrid' to 'Grid<Cell>'
HexGrid
是一个Grid<HexCell>
并且HexCell
是从Cell
派生的,所以它看起来应该可以工作。
我尝试使Grid
和Cell
抽象。 我尝试将grid
参数转换为(Grid<Cell>)
也产生了错误。 任何建议都会很棒。 谢谢!
我尝试了几种方法,但都失败了。 但是然后:为什么我们在这种情况下需要 generics 呢? 考虑这个想法:
abstract public class Grid
{
protected Cell[,] cells_;
abstract public List<Cell> GetAdjacentCells(Cell cell);
}
abstract public class Cell
{
protected Grid grid_;
public Cell(Grid grid, int x, int y)
{
grid_ = grid;
}
}
public class HexGrid : Grid
{
public override List<Cell> GetAdjacentCells(Cell cell)
{
throw new NotImplementedException();
}
}
这里没有什么需要通用的。
由于您也可以控制单元格,因此使其实现一个接口,然后将其用作“合同”,这样所有派生的或用法都可以是这样的,您只需将必要的东西推广到接口即可。
public interface ICell
{
}
abstract public class Grid<T> where T : ICell
{
protected T[,] cells_;
abstract public List<T> GetAdjacentCells(T cell);
}
abstract public class Cell : ICell
{
protected Grid<ICell> grid_;
public Cell(Grid<ICell> grid, int x, int y)
{
grid_ = grid;
}
}
public class HexGrid : Grid<ICell>
{
public override List<ICell> GetAdjacentCells(ICell cell)
{
throw new NotImplementedException();
}
}
public class HexCell : Cell
{
public HexCell(HexGrid grid, int x, int y)
: base(grid, x, y)
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.