问题:我想将两个类拆分到自己的文件中,同时避免循环引用。
我有一个包含一些类(以及一些枚举和常量)的单元。任何人都会认出Click and Clack 的 Tappet 兄弟:
unit Cartalk;
interface
type
TSolution = (solTransmission, solBrakes, solGremlins);
TTappetBrother = class(TObject)
public
function GetSolution: TSolution; virtual; abstract;
end;
TClick = class(TTappetBrother)
public
function GetSolution: TSolution; override;
end;
TClack = class(TTapperBrother)
public
function GetSolution: TSolution; override;
end;
implementation
function TClick.GetSolution: TSolution;
begin
Result := solTransmission;
end;
function TClack.GetSoltution: TSolution;
begin
Result := solGremlins;
end;
end.
现在显然我的两个类TClick
并且TClick
相当复杂。为了便于管理,我想在不破坏任何现有外部代码TClick
的情况下拆分并分配TClack
给他们自己的单元。
我的第一次破解是:
unit Cartalk;
interface
uses
Cartalk_Click, Cartalk_Clack;
type
TSolution = (solTransmission, solBrakes, solGremlins);
TTappetBrother = class(TObject)
public
function GetSolution: TSolution; virtual; abstract;
end;
TClick = Cartalk_Click.TClick; //alias brought in from Cartalk_Click.pas
TClack = Cartalk_Clack.TClack; //alias brought in from Cartalk_Clack.pas
implementation
end.
完美,我有所有相同的课程,Cartalk.pas
现在我只需要写:Cartalk_Click.pas
Cartalk_Clack.pas
unit Cartalk_Click;
interface
type
TClick = class(TTappetBrother)
public
function GetSolution: TSolution; override;
end;
implementation
function TClick.GetSolution: TSolution;
begin
Result := solTransmission;
end;
end.
当然,问题在于,TTappetBrother
并且TSolution
没有在本单元中声明。因此,我们在 中添加了对他们居住地的引用uses
,看着它失败,并触及我问题的核心:
unit Cartalk_Click;
interface
uses
Cartalk;
type
TClick = class(TTappetBrother)
public
function GetSolution: TSolution; override;
end;
implementation
function TClick.GetSolution: TSolution;
begin
Result := solTransmission;
end;
end.
现在Cartalk
和之间有一个循环引用Cartalk_Click
。
注意:当然,我没有 Cartalk 装置,还有 Click and Clack the tapper 兄弟——这只是一个例子。实际上,我的单元中有 3 个类、20 个枚举和 293 个常量。