本文介绍了两类有两个循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个不同的班级制作两个不同的单位,我如何创建循环参考?在德尔福(班级不同单位)unit1:
使用unit2;
类型Ta = class(tobject)
public
b:Tb;
结束
Unit2:
code> type Tb = class(tobject)
public
a:Ta;
结束
解决方案
确实可以绕过圆形单位参考,使用类帮助器
。
通过添加一个常见的UnitClassHelper,包括Ta和Tb的类帮助器,可以像这个:
unit Unit1;
接口
类型Ta =类(tobject)
public
b:TObject;
结束
实现
使用UnitClassHelper;
-
unit Unit2;
接口
类型Tb =类(tobject)
public
a:TObject;
结束
实现
使用UnitClassHelper;
-
unit UnitClassHelper;
接口
使用Unit1,Unit2;
类型TaHelper =类助手Ta
private
函数GetTb:Tb;
程序SetTb(obj:Tb);
public
属性B:Tb读取GetTb写入SetTb;
结束;
类型TbHelper =类的助手Tb
private
函数GetTa:Ta;
程序SetTa(obj:Ta);
public
属性A:Ta读取GetTa写入SetTa;
结束;
执行
函数TaHelper.GetTb:Tb;
begin
结果:= Self.B;
结束
procedure TaHelper.SetTb(obj:Tb);
begin
Self.B:= obj;
结束
功能TbHelper.GetTa:Ta;
begin
结果:= Self.A;
结束
程序TbHelper.SetTa(obj:Ta);
begin
Self.A:= obj;
结束
结束。
-
程序测试;
在'Unit1.pas'中使用
Unit1,
'Unit2.pas'中的Unit2,
'UnitClassHelper.pas'中的UnitClassHelper;
var
AObj:Ta;
BObj:Tb;
begin
AObj:= Ta.Create;
BObj:= Tb.Create;
try
AObj.B:= BObj;
BObj.A:= AOBj;
//做某事
finally
AObj.Free;
BObj.Free;
结束
结束。
另请参阅类帮助者的优秀摘要
:
I have two different classes made in two different units, how do i will creat circular references? in Delphi(the classes are in different units)
unit1:
Uses unit2;
type Ta = class(tobject)
public
b:Tb;
end;
Unit2:
type Tb = class(tobject)
public
a:Ta;
end;
解决方案
It is indeed possible to circumvent the circular unit reference, using class helpers
.
By adding a common UnitClassHelper including class helpers for both Ta and Tb it could be solved like this :
unit Unit1;
interface
type Ta = class(tobject)
public
b : TObject;
end;
implementation
uses UnitClassHelper;
-
unit Unit2;
interface
type Tb = class(tobject)
public
a : TObject;
end;
implementation
uses UnitClassHelper;
-
unit UnitClassHelper;
interface
uses Unit1,Unit2;
Type TaHelper = Class Helper for Ta
private
function GetTb : Tb;
procedure SetTb( obj : Tb);
public
property B : Tb read GetTb write SetTb;
End;
Type TbHelper = Class Helper for Tb
private
function GetTa : Ta;
procedure SetTa( obj : Ta);
public
property A : Ta read GetTa write SetTa;
End;
implementation
function TaHelper.GetTb: Tb;
begin
Result:= Self.B;
end;
procedure TaHelper.SetTb(obj: Tb);
begin
Self.B:= obj;
end;
function TbHelper.GetTa: Ta;
begin
Result:= Self.A;
end;
procedure TbHelper.SetTa(obj: Ta);
begin
Self.A:= obj;
end;
end.
-
program Test;
uses
Unit1 in 'Unit1.pas',
Unit2 in 'Unit2.pas',
UnitClassHelper in 'UnitClassHelper.pas';
var
AObj : Ta;
BObj : Tb;
begin
AObj:= Ta.Create;
BObj:= Tb.Create;
try
AObj.B:= BObj;
BObj.A:= AOBj;
// Do something
finally
AObj.Free;
BObj.Free;
end;
end.
See also this excellent summary of class helpers
: solving-circular-unit-references-with-class-helpers
这篇关于两类有两个循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!