我的第一个对象是TGoodFairy
(TObject),它有自己的孩子FChildren
(TList)。
有Assign
程序,可以复制任何TGoodFairy及其子代。
第二个对象是TBadFairy
,它是TGoodFairy的后代。
我正在努力如何使用TBadFairy的Assign方法来创建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;
答案 0 :(得分:5)
尝试更像这样的事情:
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;