zoukankan      html  css  js  c++  java
  • 访问类的私有属性

    如何访问类的私有属性?

    下面以 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

    三、直接使用 with Self do (此法最简单):(2017/09/04)

    type
      TPathDataHelper = class helper for TPathData
      public
        procedure SetPoint(const AIndex: Integer; const PathPoint: TPathPoint);
      end;
    
    procedure TPathDataHelper.SetPoint(const AIndex: Integer; const PathPoint: TPathPoint);
    begin
         with Self do // 必需使用 with Self do
              FPathData[AIndex] := PathPoint;
    end;

    (感谢 [深圳]cjc 提供)

  • 相关阅读:
    url protocol
    wpf webbrowser取消js报错
    c#端口扫描器wpf+socket
    c#协变 抗变
    MTK刷机快捷键
    iTextCharp c#
    wince可用的7-zip
    直播平台搭建与相关资料
    pyinstall
    面向对象常见的术语
  • 原文地址:https://www.cnblogs.com/marklove/p/9206826.html
Copyright © 2011-2022 走看看