Delphi 如何使用rtti列出属性的属性?
我目前正在使用此代码,但没有列出任何内容。我错过了什么Delphi 如何使用rtti列出属性的属性?,delphi,attributes,delphi-2010,delphi-xe,rtti,Delphi,Attributes,Delphi 2010,Delphi Xe,Rtti,我目前正在使用此代码,但没有列出任何内容。我错过了什么 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
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突然支持属性。但是所有这些.NET属性在Delphi中都不存在。他们没有将它们全部根除,而是让编译器发出警告,然后忽略它们。(另外,我相信我听到教统局的人说,无论出于何种原因,Delphi for.NET仍然在内部使用。)
作为一个副作用,在类中放置一个实际上不存在的属性是完全有效的。编译器只会忽略它,不会生成RTTI。要添加到这一点,如果您希望在代码中使用自定义属性,并且RTTI可以访问这些属性,则需要在代码中明确定义属性类。2010年的文档中有一整章都是关于这个主题的:ms-help://embarcadero.rs2010/rad/Attributes_Index.html