访问类的私有属性(RTTI和模仿类2种方法)

如何访问类的私有属性?

下面以 TPathData 为例,它有一个私有属性 PathData,储存了每一个曲线点,但一般无法修改它,需要利用下面方法,才能访问修改(若有更好的方法,歡迎分享):

一、利用 RTTI 取得类私有属性(建议使用此方法)

复制代码
type
  TPathDataHelper = class helper for TPathData
  public
    function PathData: TList<TPathPoint>;
  end;

function TPathDataHelper.PathData: TList<TPathPoint>;
var Context1: TRttiContext;
    Type1: TRttiType;
    Field1: TRttiField;
begin
     Context1 := TRttiContext.Create;
     Type1    := Context1.GetType(TPathData);
     Field1   := Type1.GetField('FPathData');

     if Assigned(Field1) then
          Result := Field1.GetValue(Self).AsObject as TList<TPathPoint>
     else Result := nil;
end;
复制代码

参考:http://blog.qdac.cc/?p=2541 (VKHelper,感谢 swish)

二、利用仿类将私有属性改成公有(仿类的成员必需与原类成员位置及顺序相同,因此当版本不同且成员不同时,必需跟着修改)

复制代码
type
  TPathDataHack = class(TInterfacedPersistent)
  public
    FOnChanged: TNotifyEvent;
    FStyleResource: TObject;
    FStyleLookup: string;
    FStartPoint: TPointF;
    FPathData: TList<TPathPoint>;
  end;

  TPathDataHelper = class helper for TPathData
  public
    function PathData: TList<TPathPoint>;
  end;

function TPathDataHelper.PathData: TList<TPathPoint>;
begin
     Result := TPathDataHack(Self).FPathData;
end;
复制代码

参考:http://stackoverflow.com/questions/37351215/how-to-access-a-private-field-from-a-class-helper-in-delphi-10-1-berlin

http://www.cnblogs.com/onechen/p/5978083.html

原文地址:https://www.cnblogs.com/findumars/p/6361258.html