Rtti 的自由对象场

Free Object's Field By Rtti

如何在 delphi (XE4) 中通过 Rtti 释放对象的字段?

我需要动态释放所有字段

我可以找到字段,但我现在不知道如何释放它们:

destructor TKnBase.Destroy;
var
  AContext: TRttiContext;
  AField: TRttiField;
begin
  for AField in AContext.GetType(Self.ClassInfo).GetFields do
  begin
     -->free filed (AField)
  end;

  inherited;
end;

我试过这个但不起作用:

destructor TKnBase.Destroy;
type
  dp = ^TObject;
var
  AContext: TRttiContext;
  AField: TRttiField;
  p: dp;
begin
  for AField in AContext.GetType(Self.ClassInfo).GetFields do
  begin
    p := dp(NativeInt(AField) + AField.Offset);
    TObject(p^).Free;
  end;

  inherited;
end;

偏移量是相对于实例指针的。您的代码应该是:

 p := dp(NativeInt(Self) + AField.Offset);

您可能更喜欢使用字段对象的 GetValue 方法来读取字段的值。所以要避免所有的指针运算。

你在这里做的事情非常有限。所有派生的 classes 都必须符合此策略。所有字段都必须是对象,并且必须属于此 class。您不能有整数字段、布尔字段等。至少你应该只尝试破坏作为对象的字段。

我的直觉告诉我,你的尝试将被证明是行不通的。