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

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

问题描述

想象下面这两类棋类游戏:

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.pas ChessPiece.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天全站免登陆