首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在公共属性上使用GetPropInfo

在公共属性上使用GetPropInfo
EN

Stack Overflow用户
提问于 2019-04-07 17:20:24
回答 1查看 749关注 0票数 3

据我所知,自Delphi2010以来,我不仅可以在发布的版本上使用RTTI,还可以在公共属性上使用RTTI。我有一个旧的Delphi7代码,它也可以在XE7下工作,但我仍然无法访问公共属性。

代码如下:

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

procedure TForm1.GetPublicProp;
var
  AColumn: TcxGridDBColumn;
  APropInfo: PPropInfo;
begin
  AColumn := MycxGridDBTableView.Columns[0];
  APropInfo := GetPropInfo(AColumn, 'Index');
  if (APropInfo = nil) then
    showmessage('not found');
end;

( TcxGridDBColumn是TcxGrid > DevExpress组件中的一列)

显然,我遗漏了什么,或者我完全误解了RTTI在XE下的工作方式,仍然无法访问公共属性?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-08 06:03:53

一个片段,它使用新的TRTTIContext记录作为入口点来获取类型,然后获取其属性。

注意,它并不显式地需要TypInfo单元。您可以使用原始的PTypeInfo获取RTTIType,但是您可以只传递AnyObject.ClassType,它将被视为PTypeInfo。

从类型中,您可以获得一个属性数组,我相信您必须迭代这些属性才能找到正确的属性。

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

type
  TColumn = class
  private
    FIndex: Integer;
  public
    property Index: Integer read FIndex write FIndex;
  end;

var
  AnyObject: TObject;
  Context: TRttiContext;
  RType: TRttiType;
  Prop: TRttiProperty;
begin
  AnyObject := TColumn.Create;
  TColumn(AnyObject).Index := 10;

  try
    // Initialize the record. Doc says it's needed, works without, though.
    Context := TRttiContext.Create;

    // Get the type of any object
    RType := Context.GetType(AnyObject.ClassType);

    // Iterate its properties, including the public ones.
    for Prop in RType.GetProperties do
      if Prop.Name = 'Index' then
      begin
        // Getting the value.
        // Note, I could have written AsInteger.ToString instead of StrToInt.
        // Just AsString would compile too, but throw an error on int properties.
        ShowMessage(IntToStr(Prop.GetValue(AnyObject).AsInteger));

        // Setting the value.
        Prop.SetValue(AnyObject, 30);
      end;
  finally
    AnyObject.Free;
  end;
end;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55557407

复制
相关文章

相似问题

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