3

问题:我想将两个类拆分到自己的文件中,同时避免循环引用。

我有一个包含一些类(以及一些枚举和常量)的单元。任何人都会认出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.pasCartalk_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 个常量。

4

1 回答 1

5

写一个单元:

unit Tappet;

interface

type
   TSolution = (solTransmission, solBrakes, solGremlins);

   TTappetBrother = class(TObject)
   public
      function GetSolution: TSolution; virtual; abstract;
   end;

implementation

end.

Click并在和Clack单位中使用它。然后编写CarTalk单元以使用所有三个并在其接口中导出所需的类型。不需要循环引用。

于 2010-10-21T20:55:37.360 回答