I'm trying to get the properties of a TObject with their name like so:
var key := GetStrProp(table.Item, keyName);
var value := GetStrProp(table.Item, valueName);
The code above returns an error saying it cannot find property 'CODE' on the object (the keyName contains 'CODE'). The same happens for the valueName.
I tested the content of the object with the code below, it does contain the property CODE and the value also contains what I expect.
var item := table.Item as TdciPROJECTRESULTAATTYPE;
var code := item.CODE;
var value := item.DESCRIPTION;
What is wrong with the first 2 lines?
CodePudding user response:
There's nothing wrong with your code, but there might be something "wrong" with the TdciPROJECTRESULTAATTYPE class.
GetStrProp
is one of Delphi's "old-style" RTTI methods from the TypInfo
unit. The old RTTI was only generating type information for published properties of objects compiled with the {M } compiler directive (and their descendants). TdciPROJECTRESULTAATTYPE most likely does not have those old-style RTTI.
If you have a modern version of Delphi, it offers more "modern" RTTI functions(in unit RTTI
), that can access way more informations about objects (Though, I don't remember at this time the exact inclusion rules). Those may allow you to access your property through RTTI.
CodePudding user response:
Thanks to Ken for pointing me in the right direction. I've created a little function that does what I need just fine. Here's the code.
class function TComboboxHelper<TTable>.GetPropertyValue(obj: TObject; name: string) : TValue;
begin
Result := nil;
var rttiContext := TRttiContext.Create;
try
var classType := obj.ClassType;
var itemType := rttiContext.GetType(classType);
var propType := itemType.GetProperty(name);
Result := propType.GetValue(obj);
finally
rttiContext.Free;
end;
end;
You can use it like so:
var key := GetPropertyValue(table.Item, keyName).AsString;
var value := GetPropertyValue(table.Item, valueName).AsString;