如何避免循环单位引用? [英] How to avoid circular unit reference?

查看:29
本文介绍了如何避免循环单位引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下以下两类国际象棋游戏:

Imagine the following two classes of a chess game:

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.pasChessPiece.pas 中定义这两个类.

I want the two classes to be defined in two separate units ChessBoard.pas and ChessPiece.pas.

如何避免我在这里遇到的循环单元引用(每个单元都需要在另一个单元的接口部分中)?

How can I avoid the circular unit reference that I run into here (each unit is needed in the other unit's interface section)?

推荐答案

将定义 TChessPiece 的单位更改为如下所示:

Change the unit that defines TChessPiece to look like the following:

TYPE
  tBaseChessBoard = class;

  TChessPiece = class
    procedure GetMoveTargets (BoardPos : TPoint; Board : TBaseChessBoard; ...    
  ...
  end;    

然后将定义 TChessBoard 的单元修改为如下所示:

then modify the unit that defines TChessBoard to look like the following:

USES
  unit_containing_tBaseChessboard;

TYPE
  TChessBoard = class(tBaseChessBoard)
  private
    FBoard : array [1..8, 1..8] of TChessPiece;
  ...
  end;  

这允许您将具体实例传递给棋子,而不必担心循环引用.由于董事会在其私有中使用 Tchesspieces,因此它实际上不必在 Tchesspiece 声明之前存在,就像占位符一样.tChessPiece 必须知道的任何状态变量当然都应该放在 tBaseChessBoard 中,在那里它们对两者都可用.

This allows you to pass concrete instances to the chess piece without having to worry about a circular reference. Since the board uses the Tchesspieces in its private, it really doesn't have to exist prior to the Tchesspiece declaration, just as place holder. Any state variables which the tChessPiece must know about of course should be placed in the tBaseChessBoard, where they will be available to both.

这篇关于如何避免循环单位引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆