用RTTI方法获取组件属性的类

来源:互联网 发布:mysql replication 编辑:程序博客网 时间:2024/04/27 14:27
最近在写脚本生成,所以用到了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;