本文介绍了是否可以获取类属性的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

type
  TMyClass = class
  ...
  public
    ...
    property P1: Integer Index 1 read GetInteger write SetInteger;
    property P2: Integer Index 2 read GetInteger write SetInteger;
    property P3: Integer Index 3 read GetInteger write SetInteger;
    ...
  end;

是否可以获取类属性的索引?例如,

Is it possible to get the index of class property? For example, something like

  I := IndexOfProperty(TMyClass.P2);


推荐答案

您可以使用RTTI来获取财产。根据您的Delphi版本,您可以使用 GetPropInfo 方法(仅适用于已发布的属性)或通过 TRttiInstanceProperty 类访问此类信息

You can use the RTTI, to get the index of a property. depending of you Delphi version you can use GetPropInfo method (only for published properties) or access such info via the TRttiInstanceProperty class

尝试以下示例。

{$APPTYPE CONSOLE}

uses
  Rtti,
  SysUtils,
  TypInfo;

type
  TMyClass = class
  private
    function GetInteger(const Index: Integer): Integer;
    procedure SetInteger(const Index, Value: Integer);

  public
    property P1: Integer Index 1 read GetInteger write SetInteger;
    property P2: Integer Index 2 read GetInteger write SetInteger;
    property P3: Integer Index 3 read GetInteger write SetInteger;
  end;



{ TMyClass }

function TMyClass.GetInteger(const Index: Integer): Integer;
begin

end;

procedure TMyClass.SetInteger(const Index, Value: Integer);
begin

end;


var
  LRttiInstanceProperty   : TRttiInstanceProperty;
  LRttiProperty : TRttiProperty;
  Ctx: TRttiContext;
  LPropInfo : PPropInfo;
begin
 try
   LPropInfo:= GetPropInfo(TMyClass, 'P1'); //only works for published properties.
   if Assigned(LPropInfo) then
    Writeln(Format('The index of the property %s is %d',[LPropInfo.Name, LPropInfo.Index]));


   Ctx:= TRttiContext.Create;
   try
     LRttiProperty:=  Ctx.GetType(TMyClass).GetProperty('P2');
     if Assigned(LRttiProperty) and (LRttiProperty is TRttiInstanceProperty) then
     begin
      LRttiInstanceProperty := TRttiInstanceProperty(LRttiProperty);
      Writeln(Format('The index of the property %s is %d',[LRttiProperty.Name, LRttiInstanceProperty.Index]));
     end;
   finally
     Ctx.Free;
   end;

 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

这篇关于是否可以获取类属性的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:38