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 提供)

  • 相关阅读:
    Mybatis框架(一)
    maven(一)
    shiro安全框架(二)
    shiro安全框架(一)
    Linux系统
    maven(二)
    Redis存储系统(二)
    Redis存储系统(一)
    1.2 性能测试(效率)
    1.3 压力测试/极限测试(可靠性)
  • 原文地址:https://www.cnblogs.com/marklove/p/9206826.html
Copyright © 2011-2022 走看看