想象下面两种棋牌游戏:
TChessBoard = class private FBoard : array [1..8,1..8] of TChessPiece; ... end; TChessPiece = class abstract public procedure GetMoveTargets (BoardPos : TPoint; Board : TChessBoard; MoveTargetList : TList <TPoint>); ... end;
我想让这两个类在两个单独的单元ChessBoard.pas和ChessPiece.pas中定义.
如何避免我遇到的圆形单元参考(在其他单元的界面部分需要每个单元)?
解决方法
将定义TChessPiece的单位更改为如下所示:
TYPE tBaseChessBoard = class; TChessPiece = class procedure GetMoveTargets (BoardPos : TPoint; Board : TBaseChessBoard; ... ... end;
然后修改定义TChessBoard的单元如下所示:
USES unit_containing_tBaseChessboard; TYPE TChessBoard = class(tBaseChessBoard) private FBoard : array [1..8,1..8] of TChessPiece; ... end;
这样就可以将具体的实例传递给棋子,而无需担心循环引用.由于董事会私人使用Tchesspieces,所以在Tchesspiece声明之前,它并不一定存在,就像持有人一样.当然,tChessPiece必须知道的任何状态变量都应该放在tBaseChessBoard中,两者都可以使用.