获取所有 TStrings 属性的列表
Get a list of all TStrings properties
我正在尝试查找对象上所有具有 TStrings 后代类型的属性。
这是我到目前为止尝试过的方法:
在表单上放置备忘录和图表,然后放置此代码。
procedure TForm1.FormCreate(Sender: TObject);
var
aObject: TObject;
begin
for aObject in GetItemsObjects(Chart1) do
Memo1.Lines.Add(aObject.ClassName);
end;
class function TForm1.GetItemsObjects(aObject: TObject): TArray<TObject>;
var
RttiProperty: TRttiProperty;
RttiType: TRttiType;
ResultList: TList<TObject>;
PropertyValue: TValue;
PropertyObject: TObject;
s: String;
begin
ResultList := TList<TObject>.Create;
try
RttiType := RttiContext.GetType(aObject.ClassType);
for RttiProperty in RttiType.GetProperties do
begin
PropertyValue := RttiProperty.GetValue(aObject);
if (not PropertyValue.IsObject) or (PropertyValue.IsEmpty) then
continue;
try
PropertyObject := PropertyValue.AsObject;
s := PropertyObject.ClassName;
if (PropertyObject is TStrings) then
ResultList.Add(PropertyObject)
else
ResultList.AddRange(GetItemsObjects(PropertyObject));
except
end;
end;
finally
Result := ResultList.ToArray;
ResultList.Free;
end;
end;
问题是我遇到了堆栈溢出。尽管我试图用这段代码停止递归:
if (PropertyObject is TStrings) then
ResultList.Add(PropertyObject)
else
ResultList.AddRange(GetItemsObjects(PropertyObject));
您的代码导致堆栈溢出,因为您正在递归调用 GetItemsObjects,它还从 TControl
.
扫描 Parent
等属性
如果你真的想递归地对 TStrings 属性进行深度扫描,那么你需要确保不要再次访问相同的对象 - 用列表或其他东西跟踪它们。
我正在尝试查找对象上所有具有 TStrings 后代类型的属性。
这是我到目前为止尝试过的方法:
在表单上放置备忘录和图表,然后放置此代码。
procedure TForm1.FormCreate(Sender: TObject);
var
aObject: TObject;
begin
for aObject in GetItemsObjects(Chart1) do
Memo1.Lines.Add(aObject.ClassName);
end;
class function TForm1.GetItemsObjects(aObject: TObject): TArray<TObject>;
var
RttiProperty: TRttiProperty;
RttiType: TRttiType;
ResultList: TList<TObject>;
PropertyValue: TValue;
PropertyObject: TObject;
s: String;
begin
ResultList := TList<TObject>.Create;
try
RttiType := RttiContext.GetType(aObject.ClassType);
for RttiProperty in RttiType.GetProperties do
begin
PropertyValue := RttiProperty.GetValue(aObject);
if (not PropertyValue.IsObject) or (PropertyValue.IsEmpty) then
continue;
try
PropertyObject := PropertyValue.AsObject;
s := PropertyObject.ClassName;
if (PropertyObject is TStrings) then
ResultList.Add(PropertyObject)
else
ResultList.AddRange(GetItemsObjects(PropertyObject));
except
end;
end;
finally
Result := ResultList.ToArray;
ResultList.Free;
end;
end;
问题是我遇到了堆栈溢出。尽管我试图用这段代码停止递归:
if (PropertyObject is TStrings) then
ResultList.Add(PropertyObject)
else
ResultList.AddRange(GetItemsObjects(PropertyObject));
您的代码导致堆栈溢出,因为您正在递归调用 GetItemsObjects,它还从 TControl
.
Parent
等属性
如果你真的想递归地对 TStrings 属性进行深度扫描,那么你需要确保不要再次访问相同的对象 - 用列表或其他东西跟踪它们。