to Jonson_sunshine
这样做是可以实现对象内包含同类对象,但是在多层嵌套的情况(尤其是数组中各个子对象内嵌套层数不相同的情况)下,层层深入调用ATest.SetTestAry(Num)很不方便,也不实际。如果在事先知道对象个数的情况下不知道下面的代码能否正常运行,不进入死循环。
TTest = class(TObject)
private
FSubNum :Byte;// 数组的长度
FTestAry :TTestAry;
FTag :integer;
public
constructor Create;
destructor Destroy;override;
procedure GetSubNum;//获得数组长度
procedure FreeTestAry;
procedure SetTestAry(Num :integer);
property SubNum :Byte read FSubNum;
property TestAry :TTestAry read FTestAry write FTestAry;
property Tag :integer read FTag write FTag;
end;
implementation
{ TTest }
constructor TTest.Create;
begin
inherited Create;
GetSubNum;
SetTestAry(FSubNum);
end;
destructor TTest.Destroy;
begin
FreeTestAry
//调用自定义过程
inherited;
end;
procedure TTest.FreeTestAry;
var
i :integer;
begin
if assigned(TestAry) then //判断TestAry是否为nil(即是否有元素,有则释放)
for i :=Low(TestAry) to High(TestAry) do
begin
TestAry.Destroy;
end;
end;
procedure TTest.GetSubNum;
begin
......
FSubNum:=n//n是根据不同对象生成的不同的值
end;
procedure TTest.SetTestAry(Num: integer)
//自定义的创建过程,供需要时调用
var
ATestAry :TTestAry;
i :integer;
begin
SetLength(ATestAry,Num);
for i :=Low(ATestAry) to High(ATestAry) do
begin
ATestAry :=TTest.Create;
ATestAry.Tag :=i*2 + 1;
end;
TestAry :=ATestAry
//创建的子对象数组赋值给数组成员FTestAry
end;