delphi - 是否可以获得类属性的索引?

标签 delphi properties

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.

关于delphi - 是否可以获得类属性的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19713584/

相关文章:

java - Osgi 属性占位符

delphi - FMX : Fill whole bitmap with a background color

arrays - 数组类型赋值如何工作?

Delphi TCollection - 可以防止在运行时更改项目吗?

delphi - 如何在Delphi中设置TADOConnection的“应用程序名称”属性?

delphi - 如何找出 Delphi 函数可能抛出哪些异常?

ios - keepCount 是否为我的 NSDate 提供了正确的信息?

java - 使用Ant写入属性文件以在JAVA中使用

Objective-C 字典作为属性/方法访问

c# - 如何验证属性值?