gpt4 book ai didi

delphi - 如何调用给定实例的构造函数?

转载 作者:行者123 更新时间:2023-12-03 15:49:35 25 4
gpt4 key购买 nike

我的第一个对象是 TGoodFairy (TObject),它有自己的子对象 FChildren (TList)。有一个Assign过程,它复制任何TGoodFairy及其子项。

第二个对象是TBadFairy,它是TGoodFairy 的后代。

我正在努力如何使用 TBadFairy 的分配方法来创建 TBadFairy 子项。我想将 ClassType 与 Create 结合使用,以便为 TBadFairy 创建正确的子级(目前仅创建 TGoodFairy 子级)

  TGoodFairy = class (TObject)
private
FChildren:TList;
FName:string;
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source:TGoodFairy);
published
property Name:string read FName write FName;
end;

TBadFairy = class (TGoodFairy)
procedure Assign(Source:TBadFairy);
end;

------------------------

constructor TGoodFairy.Create;
begin
inherited;
FChildren:=TList.Create;
end;

destructor TGoodFairy.Destroy;
var i:integer;
begin
for i:=0 to FChildren.Count-1 do TGoodFairy(FChildren[i]).Free;
FChildren.Clear;
FChildren.Free;
inherited;
end;

procedure TGoodFairy.Assign(Source:TGoodFairy);
var i:integer;
f:TGoodFairy;
C:TClass;
begin
FName:=Source.Name;
for i:=0 to Source.FChildren.Count-1 do
begin
//C := Source.ClassType;
//f := C.Create;
f := TGoodFairy.Create; //<-- this should be parametrized somehow
f.Assign(Source.FChildren[i]);
FChildren.Add(f);
end;
end;


procedure TBadFairy.Assign(Source:TBadFairy);
begin
inherited Assign(Source);
end;

最佳答案

尝试更多类似这样的事情:

type
TFairy = class(TObject)
private
FChildren: TObjectList;
FName: string;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Assign(Source: TFairy); virtual;
published
property Name: string read FName write FName;
end;

TFairyClass = class of TFairy;

TGoodFairy = class(TFairy)
end;

TBadFairy = class(TFairy)
end;

constructor TFairy.Create;
begin
inherited;
FChildren := TObjectList.Create(True);
end;

destructor TFairy.Destroy;
begin
FChildren.Free;
inherited;
end;

procedure TFairy.Assign(Source: TFairy);
var
i: integer;
f, child: TFairy;
begin
FName := Source.Name;
FChildren.Clear;
for i := 0 to Source.FChildren.Count-1 do
begin
child := TFairy(Source.FChildren[i]);
f := TFairyClass(child.ClassType).Create;
try
f.Assign(child);
FChildren.Add(f);
except
f.Free;
raise;
end;
end;
end;

关于delphi - 如何调用给定实例的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44913998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com