【问题标题】:using GetPropInfo on public property在公共财产上使用 GetPropInfo
【发布时间】:2019-08-28 15:46:24
【问题描述】:

据我所知,自 Delphi 2010 以来,我不仅可以在已发布的内容上使用 RTTI,还可以在公共财产上使用 RTTI。我有一个旧的 Delphi 7 代码,它也可以在 XE7 下工作,但我仍然无法访问公共属性。

代码如下:

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 下的工作方式,并且仍然无法访问公共属性?

【问题讨论】:

  • 您需要增强的 RTTI。您可以在 System.RTTI 单元(或 Delphi 2010 中的 RTTI)中找到它
  • 啊,新功能,不是旧功能被改写了。我去看看,谢谢!
  • 如果您需要,TypInfo 单元中的代码仍然可以正常工作。
  • 不,它没有,使用上面的示例找不到任何公共财产。

标签: delphi rtti


【解决方案1】:

一个 sn-p 使用新的 TRTTIContext 记录作为入口点来获取类型,然后是它的属性。

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

从类型中,您可以获得一组属性,我相信您必须对其进行迭代才能找到正确的。

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;

【讨论】:

  • 您也可以将 IntToStr(Prop.GetValue(AnyObject).AsInteger) 替换为 string((Prop.GetValue(AnyObject).AsVariant)
猜你喜欢
  • 1970-01-01
  • 2020-12-17
  • 2011-03-13
  • 2011-09-26
  • 1970-01-01
  • 2011-12-21
  • 2016-02-13
  • 2018-05-18
  • 2010-10-15
相关资源
最近更新 更多