Einzelnen Beitrag anzeigen

Benutzerbild von Uwe Raabe
Uwe Raabe

Registriert seit: 20. Jan 2006
Ort: Lübbecke
11.021 Beiträge
 
Delphi 12 Athens
 
#5

AW: Geerbter Getter für lokale Objekt-Konstante?

  Alt 23. Jul 2020, 10:43
Ich kann zwar immer noch nicht ganz überblicken, was du da nun brauchst bzw. willst, aber ich hätte hier einen etwas anderen Ansatz (hab nur leider gerade kein XE5 zur Hand):
Delphi-Quellcode:
UNIT Unit_1;

Interface

uses
  System.Rtti;

type
  FuncInfoAttribute = class(TCustomAttribute)
  private
    FGL: string;
    Fn_Var: Integer;
  public
    constructor Create(AGL: string; An_Var: Integer);
    property GL: string read FGL;
    property n_Var: Integer read Fn_Var;
  end;

type
  TRttiHelper = record
  public
    class function FindAttribute<T: TCustomAttribute>(Source: TClass): T; overload; static;
    class function FindAttribute<T: TCustomAttribute>(Source: TRttiObject): T; overload; static;
  end;

//------------------------------------------------------------------------------------
Type
  [FuncInfo('Funktion mit ZWEI Variablen', 2)]
  TFunk_2 = Class(TObject)
  Strict Private
    function GetGL: String;
    Function Get_n_var: Integer;
  Public
    property GL: String read GetGL;
    Property n_Var: Integer Read Get_n_var;
  End;
  //------------------------------------------------------------------------------------

Type
  [FuncInfo('Funktion mit DREI Variablen', 3)]
  TFunk_3 = Class(TFunk_2)
  End;

  //------------------------------------------------------------------------------------

Implementation

function TFunk_2.GetGL: String;
var
  attr: FuncInfoAttribute;
begin
  attr := TRttiHelper.FindAttribute<FuncInfoAttribute>(ClassType);
  Result := attr.GL;
end;

Function TFunk_2.Get_n_var: Integer;
var
  attr: FuncInfoAttribute;
begin
  attr := TRttiHelper.FindAttribute<FuncInfoAttribute>(ClassType);
  Result := attr.n_Var;
End;


constructor FuncInfoAttribute.Create(AGL: string; An_Var: Integer);
begin
  FGL := AGL;
  Fn_Var := An_Var;
end;

class function TRttiHelper.FindAttribute<T>(Source: TClass): T;
var
  context: TRttiContext;
  myType: TRttiType;
begin
  Result := nil;
  context := TRttiContext.Create;
  myType := context.GetType(Source);
  if myType <> nil then begin
    Result := FindAttribute<T>(myType);
  end;
end;

class function TRttiHelper.FindAttribute<T>(Source: TRttiObject): T;
var
  attr: TCustomAttribute;
  attributes: TArray<TCustomAttribute>;
begin
  Result := nil;
  attributes := Source.GetAttributes;
  for attr in attributes do begin
    if attr is T then begin
      Result := T(attr);
      Break;
    end;
  end;
end;

Initialization
  TRttiContext.KeepContext;

Finalization
  TRttiContext.DropContext;

End.
Uwe Raabe
Certified Delphi Master Developer
Embarcadero MVP
Blog: The Art of Delphi Programming
  Mit Zitat antworten Zitat