Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Object-Pascal / Delphi-Language (https://www.delphipraxis.net/32-object-pascal-delphi-language/)
-   -   Delphi Indexed Properties über RTTI abfragen (https://www.delphipraxis.net/216765-indexed-properties-ueber-rtti-abfragen.html)

kompi 26. Feb 2025 14:36

Delphi-Version: 12 Athens

Indexed Properties über RTTI abfragen
 
Ich habe ein Objekt in Delphi mit einem Index -Property. Das Property hat dazu einen Getter definiert.

Ich möchte nun diese Property mittels RTTI abfragen.

Hier der Code, den ich bisher habe

Delphi-Quellcode:
Class function Tpropertyrec.trygetpropertyfromindex(apropclass : Trttiinstancetype; anode : pointer; aproperty : string; aindex : Tvalue;out res: string): boolean;
var
    Lprop : Trttiindexedproperty;
  value : Tvalue;
begin
  lprop := apropclass.GetIndexedProperty(aproperty);
  result := false;
  if assigned(lprop) then
  begin
    Value := lprop.GetValue(anode,[0]);
    res := Value.asstring;
  end;
end;

Class function Tpropertyrec.trygetpropertyfromindex(aobject : Tobject; aproperty : string; aindex : Tvalue; out res: string): boolean;
var
   lcontext : Trtticontext;
  lclass   : Trttiinstancetype;
begin
    lcontext := Trtticontext.create;
  try
       lclass := lcontext.GetType(aobject.ClassType) as Trttiinstancetype;
     result := trygetpropertyfromindex(lclass, aobject, aproperty,aindex ,res);
  finally
    lcontext.free;
  end;
end;
Ich rufe nun die untere Funktion auf, die dann die obere Funktion aufruft.
Bei der Zuweisung an Value in der oberen Funktion erhalte ich eine Zugriffsverletzung. Was mache ich falsch?

Danke an alle

mytbo 26. Feb 2025 19:55

AW: Indexed Properties über RTTI abfragen
 
Zitat:

Zitat von kompi (Beitrag 1546591)
Bei der Zuweisung an Value in der oberen Funktion erhalte ich eine Zugriffsverletzung. Was mache ich falsch?

Delphi-Quellcode:
var
  strList: TStringList;
begin
  strList := TStringList.Create;
  try
    strList.Add('Peter');
    strList.Add('Klaus');
    strList.Add('Petra');

    var rttiType: TRttiType := TRttiContext.Create.GetType(TypeInfo(TStringList));
    if rttiType <> Nil then
    begin
      var rttiProp: TRttiIndexedProperty := rttiType.GetIndexedProperty('Strings');
      if (rttiProp <> Nil)
        and (rttiProp.PropertyType.TypeKind = tkUString) then
      begin
        var value: TValue := rttiProp.GetValue(strList, [1]);
        ShowMessage(value.AsString);
      end;
    end;
  finally
    strList.Free;
  end;
In diesem Fall zum Beispiel, wenn die Liste leer wäre.

Bis bald...
Thomas


Alle Zeitangaben in WEZ +1. Es ist jetzt 10:36 Uhr.

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