Reputation: 1122
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.
Upvotes: 1
Views: 209
Reputation: 21748
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;
Upvotes: 5
Reputation: 34929
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.
Upvotes: 3