Question

I get passed a TObject. I know this object descends from TBaseClass. What I want to do is display all the published properties for every class up until TBaseClass. There could be better ways of doing this, but what I'm trying is this:

lObj := aObject;
while lObj.ClassType <> TBaseClass do
begin
  lRttiType := lRttiContext.GetType(aObject.ClassType);
  lProps := lRttiType.GetDeclaredProperties;

  lStartIdx := Length(lAllProps);
  SetLength(lAllProps, Length(lAllProps) + Length(lProps));

  for I := Low(lProps) to High(lProps) do
    lAllProps[lStartIdx + I] := lProps[I];

  lObj := lObj as lObj.ClassParent;
  // lObj := lObj.ClassParent.InitInstance(lObj); // *see below
end;

The problem with this code, is that lObj.ClassType doesn't change after lObj as lObj.ClassParent. Could someone explain why this doesn't work and provide something that does work?

*This seemed to work in that it got lObj.ClassType to be the parent's class, however it lead to problems and I later read the documentation and found it shouldn't even be called in the first place.

Was it helpful?

Solution 2

You just need to make a loop of the class type.

lObj := aObject.ClassType;
while ....
  ...
  lObj := lObj.ClassParent;  
end;

See documentation for an example: ClassParent.

OTHER TIPS

You don't need to iterate the class hierarchy and use GetDeclaredProperties - GetProperties already does that for you.

for lProp in lRttiType.GetProperties do
  if prop.Parent.AsInstance.MetaclassType = TBaseClass then
    Break;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top