【问题标题】:How can I list the Attributes of a property using the rtti?如何使用 rtti 列出属性的属性?
【发布时间】:2010-10-09 22:55:45
【问题描述】:

我目前正在使用此代码,但没有列出任何内容。我错过了什么?

program ListAttrs;

{$APPTYPE CONSOLE}

uses
  Rtti,
  SysUtils;

type
  TPerson = class
  private
    FName: String;
    FAge: Integer;
  public
    [NonEmptyString('Must provide a Name')]
    property Name : String read FName write FName;
    [MinimumInteger(18, 'Must be at least 18 years old')]
    [MaximumInteger(65, 'Must be no older than 65 years')]
    property Age : Integer read FAge write FAge;
  end;


procedure test;
var
  ctx       : TRttiContext;
  lType     : TRttiType;
  lAttribute: TCustomAttribute;
  lProperty : TRttiProperty;
begin
   ctx       := TRttiContext.Create;
   lType     := ctx.GetType(TPerson);
   for lProperty in lType.GetProperties do
    for lAttribute in lProperty.GetAttributes do
    Writeln(lAttribute.ToString);
end;

begin
  try
     Test;
     Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

【问题讨论】:

    标签: delphi attributes delphi-2010 delphi-xe rtti


    【解决方案1】:

    查看您的编译器警告。当我构建它时,我看到:

    [DCC Warning] ListAttrs.dpr(15): W1025 Unsupported language feature: 'custom attribute'
    [DCC Warning] ListAttrs.dpr(17): W1025 Unsupported language feature: 'custom attribute'
    [DCC Warning] ListAttrs.dpr(18): W1025 Unsupported language feature: 'custom attribute'
    

    这是由于一个历史怪癖。 Delphi for .NET 编译器支持属性,它们在 VCL 中广泛用于各种 .NET 事物。 Delphi for Win32 编译器必须能够读取并忽略它们。

    然后Delphi 2010出来了,Delphi Win32突然支持属性了。但是所有这些 .NET 属性在 Delphi 中都不存在。他们没有将它们全部根除,而是让编译器只发出警告然后忽略它们。 (另外,我相信我从 Emb 那里听到有人说 Delphi for .NET 出于任何原因仍在内部使用。)

    作为一个副作用,在你的类中放置一个实际上并不存在的属性是完全有效的。它只会被编译器忽略,不会为其生成 RTTI。

    【讨论】:

    • 要补充一点,如果你想在你的代码中使用自定义属性,并且让 RTTI 可以访问它们,那么你需要在你的代码中显式地定义属性类。 2010 年的文档中有一整章关于此主题:ms-help://embarcadero.rs2010/rad/Attributes_Index.html
    猜你喜欢
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    相关资源
    最近更新 更多