如何訪問類的私有屬性?
下面以 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