最近在写脚本生成,所以用到了RTTI的系列方法,记载记之。
class function TSomeClass.GetCtmWnd(Component: TComponent): TPersistent;
var
PropList: PPropList;
ClassTypeInfo: PTypeInfo;
classTypeData: PTypeData;
vSize: integer;
vPropName: string;
vObject: TObject;
i: integer;
begin
result := nil;
ClassTypeInfo := Component.ClassInfo;
ClassTypeData := GetTypeData(ClassTypeInfo);
if ClassTypeData.PropCount <> 0 then
begin
vSize := SizeOf(PPropInfo) * ClassTypeData.PropCount;
GetMem(PropList, vSize);
try
GetPropInfos(Component.ClassInfo, PropList);
for i := 0 to ClassTypeData.PropCount - 1 do
begin
if PropList[i]^.PropType^.Kind = tkClass then
begin
vPropName := PropList[i]^.Name;
vObject := GetObjectProp(Component, vPropName);
if vObject is TPersistent then
begin
result := TPersistent(vObject);
break;
end;
end;
end;
finally
FreeMem(PropList, vSize);
end;
end;
end;
class function TSomeClass.GetCtmWnd(Component: TComponent): TPersistent;
var
PropList: PPropList;
ClassTypeInfo: PTypeInfo;
classTypeData: PTypeData;
vSize: integer;
vPropName: string;
vObject: TObject;
i: integer;
begin
result := nil;
ClassTypeInfo := Component.ClassInfo;
ClassTypeData := GetTypeData(ClassTypeInfo);
if ClassTypeData.PropCount <> 0 then
begin
vSize := SizeOf(PPropInfo) * ClassTypeData.PropCount;
GetMem(PropList, vSize);
try
GetPropInfos(Component.ClassInfo, PropList);
for i := 0 to ClassTypeData.PropCount - 1 do
begin
if PropList[i]^.PropType^.Kind = tkClass then
begin
vPropName := PropList[i]^.Name;
vObject := GetObjectProp(Component, vPropName);
if vObject is TPersistent then
begin
result := TPersistent(vObject);
break;
end;
end;
end;
finally
FreeMem(PropList, vSize);
end;
end;
end;
本文介绍了一种使用RTTI(运行时类型信息)在Delphi中获取组件属性值的方法,通过遍历组件的属性并查找特定类型的属性来实现。此方法可用于脚本生成等场景。
1161

被折叠的 条评论
为什么被折叠?



