微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

delphi – 是否有可能获得类属性的索引?

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;

是否有可能获得类属性的索引?例如,像

I := IndexOfProperty(TMyClass.P2);

解决方法

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

试试这个样本.

{$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.

原文地址:https://www.jb51.cc/delphi/239358.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐