繁体   English   中英

我应该如何使用从通用基础 class 派生的 class 调用基础 class 构造函数?

[英]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派生的,所以它看起来应该可以工作。

我尝试使GridCell抽象。 我尝试将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM