Einzelnen Beitrag anzeigen

Benutzerbild von s.h.a.r.k
s.h.a.r.k

Registriert seit: 26. Mai 2004
3.159 Beiträge
 
#1

[RTTI] RttiProperty aus Property von Instanz erzeugen

  Alt 25. Mär 2010, 15:13
Hallo,

hänge gerade mal wieder an einem neuen Problem mit Rtti und ich weiß nicht, wie ich das machen sollte. Ich habe mehrere Properties, die mit Werten aus der Datenbank befüllt werden. Die Setter-Methoden dieser Properties sollen auf eine generische Methode verweisen, die das Setzen der Werte für alle relevanten Properties übernehmen kann. Wichtig hierbei ist die Prüfung auf das Attribut NotNull, d.h. beim Setzen eine Wertes wird geprüft, ob ein Null-Wert gesetzt werden darf oder nicht.

Hier ein vereinfachtes Szenario, sodass das verständlicher wird:

Delphi-Quellcode:
TBlub = class(TObject)
private
  FNotNullProperties : TStringList; // wird im Konstruktor mit
  FPropA : Variant;
  FPropB : Variant;
  procedure GenericSetter(const AValue: Variant; const ADestVar: PVariant; const AProperty: TRttiProperty);
  procedure SetPropA(const AValue: Variant);
  procedure SetPropB(const AValue: Variant);
public
  [NotNull]
  property PropA : Variant read FPropA write SetPropA;
  property PropB : Variant read FPropB write SetPropB;
end;

procedure TBlub.GenericSetter(const AValue: Variant; const ADestVar: PVariant; const AProperty: TRttiProperty);
var
  rContext : TRttiContext;
  rType : TRttiType;
begin
  if (AValue <> ADestVar^) then
  begin
    if (AValue <> Null) then
    begin
      ADestVar^ := AValue;
    end
    else begin
      // Prüfen, ob Property überhaupt Null werden darf, denn wenn nicht dann muss eine Exception
      // geworfen werden
      if (FNotNullProperties.IndexOf(AProperty.Name) <> -1) then
        raise Exception.Create('...');
      ADestVar^ := Null;
    end;
  end;
end;

procedure TBlub.SetPropA(const AValue: Variant);
begin
  GenericSetter(AValue, FPropA, GetRttiProperty(PropA)); // GetRttiPropertyist eine fiktive Funktion
end;

procedure TBlub.SetPropB(const AValue: Variant);
begin
  GenericSetter(AValue, FPropB, GetRttiProperty(PropB)); // GetRttiPropertyist eine fiktive Funktion
end;
So, nun ist es ja so, dass, wie im Quelltext schon geschrieben, GetRttiProperty eine fiktive Funktion ist, die ich suche. Ich will eben aus der Property PropA bzw. PropB ein TRttiProperty-Objekt machen, ohne dabei auf einen String zurückgreifen zu müssen. Sollte sich nämlich mal etwas an den Properties ändern, so kann ich nicht einfach das Refactoring anwerfen, sondern darf selbst nach Strings suchen, was alles andere als sauber wäre.

Ich hoffe, dass mir hier jemand weiter helfen kann. Bin gerade echt am verzweifeln
»Remember, the future maintainer is the person you should be writing code for, not the compiler.« (Nick Hodges)
  Mit Zitat antworten Zitat