Hätte man doch einfach mal ausprobieren können, oder?
Delphi-Quellcode:
program Project2;
{$APPTYPE CONSOLE}
{$R *.res}
uses System.SysUtils, System.Rtti;
type
NumericAttribute =
class(System.TCustomAttribute)
public var
someNumber: Integer;
public
constructor Create(
const someNumber: Integer);
end;
[Numeric(42)]
TBase =
class(TObject)
// Stub
end;
[Numeric(99)]
TSub =
class(TBase)
// TStub
end;
{ TNumericAttribute }
constructor NumericAttribute.Create(
const someNumber: Integer);
begin
inherited Create();
self.someNumber := someNumber;
end;
procedure printNumericInfo(
const ofType: TRttiType);
var
attribute: TCustomAttribute;
numeric: NumericAttribute;
begin
for attribute
in ofType.GetAttributes()
do begin
if not (attribute
is NumericAttribute)
then Continue;
numeric := attribute
as NumericAttribute;
Write( ofType.ToString() );
Write('
has a numeric value of ');
WriteLn(numeric.someNumber);
end;
end;
procedure justRttiThings();
var
ctx: TRttiContext;
base: TBase;
sub: TSub;
begin
ctx := TRttiContext.Create();
base := TBase.Create();
sub := TSub.Create();
printNumericInfo( ctx.GetType(base.ClassType) );
printNumericInfo( ctx.GetType(sub.ClassType) );
end;
begin
try
justRttiThings();
except
on E:
Exception do
Writeln(E.ClassName, '
: ', E.
Message);
end;
readln;
end.
ergibt bei mir
Code:
TBase has a numeric value of 42
TSub has a numeric value of 99
Oder habe ich das falsch verstanden?