Einzelnen Beitrag anzeigen

Der schöne Günther

Registriert seit: 6. Mär 2013
6.110 Beiträge
 
Delphi 10 Seattle Enterprise
 
#2

AW: Attribute überschreiben

  Alt 3. Aug 2015, 15:33
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?
  Mit Zitat antworten Zitat