加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 如何使用rtti列出属性的属性?

发布时间:2020-12-15 09:27:37 所属栏目:大数据 来源:网络整理
导读:我目前正在使用此代码,但没有列出任何内容.我错过了什么? program ListAttrs;{$APPTYPE CONSOLE}uses Rtti,SysUtils;type TPerson = class private FName: String; FAge: Integer; public [NonEmptyString('Must provide a Name')] property Name : String
我目前正在使用此代码,但没有列出任何内容.我错过了什么?

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.

解决方法

看看你的编译器警告.当我构建这个时,我看到:

[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突然支持属性.但是Delphi中并不存在所有这些.NET属性.他们让编译器只发出警告然后忽略它们,而不是全部根除它们. (另外,我相信我听到Emb.有人说Delphi for .NET仍然在内部用于任何原因.)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读