5
我目前使用這段代碼,但沒有列出任何東西。我錯過了什麼?如何使用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 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.
非常感謝梅森。 – Salvador 2010-10-10 04:45:00
爲了補充說明,如果您想在代碼中使用自定義屬性,並讓它們可以被RTTI訪問,那麼您需要在代碼中明確定義屬性類。有關此主題的2010年文檔中有一整章:ms-help://embarcadero.rs2010/rad/Attributes_Index.html – 2010-10-11 20:37:56