【发布时间】:2011-12-28 09:59:39
【问题描述】:
我正在尝试在 D2010 中使用 RTTI 克隆对象。到目前为止,这是我的尝试:
uses SysUtils, TypInfo, rtti;
type
TPerson = class(TObject)
public
Name: string;
destructor Destroy(); Override;
end;
destructor TPerson.Destroy;
begin
WriteLn('A TPerson was freed.');
inherited;
end;
procedure CloneInstance(SourceInstance: TObject; DestinationInstance: TObject; Context: TRttiContext); Overload;
var
rSourceType: TRttiType;
rDestinationType: TRttiType;
rField: TRttiField;
rSourceValue: TValue;
Destination: TObject;
rMethod: TRttiMethod;
begin
rSourceType := Context.GetType(SourceInstance.ClassInfo);
if (DestinationInstance = nil) then begin
rMethod := rSourceType.GetMethod('Create');
DestinationInstance := rMethod.Invoke(rSourceType.AsInstance.MetaclassType, []).AsObject;
end;
for rField in rSourceType.GetFields do begin
if (rField.FieldType.TypeKind = tkClass) then begin
// TODO: Recursive clone
end else begin
// Non-class values are copied (NOTE: will cause problems with records etc.)
rField.SetValue(DestinationInstance, rField.GetValue(SourceInstance));
end;
end;
end;
procedure CloneInstance(SourceInstance: TObject; DestinationInstance: TObject); Overload;
var
rContext: TRttiContext;
begin
rContext := TRttiContext.Create();
CloneInstance(SourceInstance, DestinationInstance, rContext);
rContext.Free();
end;
var
Original: TPerson;
Clone: TPerson;
begin
ReportMemoryLeaksOnShutdown := true;
Original := TPerson.Create();
CloneInstance(Original, Clone);
Clone.Free();
Original.Free();
ReadLn;
end.
有点令人失望的是,我没有看到不止一次出现“一个 TPerson 被释放了。”到输出(通过单步执行程序来确认) - 使用重写的析构函数只销毁原始文件。
谁能帮我调用被覆盖的析构函数? (也许可以解释为什么一开始就没有调用它。)谢谢!
【问题讨论】:
标签: delphi delphi-2010 rtti