首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否有可能得到类属性的索引?

是否有可能得到类属性的索引?
EN

Stack Overflow用户
提问于 2013-10-31 18:00:46
回答 2查看 971关注 0票数 7
代码语言:javascript
运行
复制
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;

是否有可能得到类属性的索引?例如,类似于

代码语言:javascript
运行
复制
  I := IndexOfProperty(TMyClass.P2);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-31 19:53:22

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

试试这个样本。

代码语言:javascript
运行
复制
{$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.
票数 6
EN

Stack Overflow用户

发布于 2013-10-31 19:56:55

属性的RTTI包含索引。您的属性被声明为public,因此不能通过TypInfo单元提供的旧风格的RTTI访问它们。但是,它们可以通过Rtti单元提供的更新样式的RTTI (D2010和更高版本)访问:

代码语言:javascript
运行
复制
uses
  Rtti;

var
  Ctx: TRttiContext;
  I: Integer;
begin
  Ctx := TRttiContext.Create;
  I := (Ctx.GetType(TMyClass).GetProperty('P2') as TRttiInstanceProperty).Index;
end;

如果您的属性被声明为published,那么您可以使用TypInfo RTTI:

代码语言:javascript
运行
复制
uses
  TypInfo;

var
  I: Integer;
begin
  I := GetPropInfo(TMyClass, 'P2').Index;
end;
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19713584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档