Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Programmieren allgemein (https://www.delphipraxis.net/40-programmieren-allgemein/)
-   -   Delphi Rtti und Attribute in Delphi 2010 (https://www.delphipraxis.net/162496-rtti-und-attribute-delphi-2010-a.html)

martin_ 25. Aug 2011 09:43

Rtti und Attribute in Delphi 2010
 
Hallo,
bin gerade dabei mir das Beispiel von http://www.malcolmgroves.com/blog/?p=476 anzusehen und habe ein Verständnisproblem mit Attributen.
Und zwar bei
Delphi-Quellcode:
  MyAttribute = class(TCustomAttribute)
  private
    FName: string;
    FAge: Integer;
  public
    constructor Create(const Name : string; Age : Integer);
    property Name : string read FName write FName;
    property Age : Integer read FAge write FAge;
  end;
Delphi-Quellcode:
 TMyClass = class
  public
    [MyAttribute('Malcolm', 39)]
    procedure MyProc(const s : string);
    [MyAttribute('Julie', 37)]
    procedure MyOtherProc;
  end;
Was passiert bei [MyAttribute('Malcolm', 39)]? Ist es richtig das in der Methode MyProc ein neues Objekt der Klasse MyAttribute mit den Inhalten ('Malcolm', 39) erzeugt wird?
Das wäre dann gleich mit:
Delphi-Quellcode:
procedure MyProc (...)
var
 a : MyAttribute
begin
  a := MyAttribute.create('Malcolm', 39);
end;
Nur wie erfolgt der Zugriff auf das mittels [MyAttribute('Malcolm', 39)] erzeugte Objekt? Kann man sich da auch so etwas wie var a : MyAttribute anlegen, um nicht jeden Zugriff über TRttiContext durchzuführen?

Stevie 25. Aug 2011 10:01

AW: Rtti und Attribute in Delphi 2010
 
Attribute sind Teil der RTTI, von daher musst du sie auch darüber auslesen.

Delphi-Quellcode:
var
  ctx: TRttiContext;
  t: TRttiType;
  m: TRttiMethod;
  a: TCustomAttribute;
begin
  t := ctx.GetType(TMyClass);
  m := t.GetMethod('MyProc');
  for a in m.GetAttributes do
  begin
    if a is MyAttribute then
    begin
      ShowMessageFmt('Name: %s, age: %d', [MyAttribute(a).Name, MyAttribute(a).Age]);
    end;
  end;
end;


Alle Zeitangaben in WEZ +1. Es ist jetzt 19:14 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz