• 获取对象的 RTTI 属性与事件的函数


     uses TypInfo; {获取类的信息, 需要这个单元}


    //获取对象的 RTTI 属性与事件的函数
    function GetPropertyAndEventList(obj: TObject; pList,eList: TStringList): Boolean;
    var
      ClassTypeInfo: PTypeInfo; {类的信息结构指针}
      ClassDataInfo: PTypeData; {类的数据结构指针}
      propertyList : PPropList; {TPropInfo 是属性的数据结构;
                                 PPropList 是其指针;
                                 TPropList 是属性结构指针的列表数组;
                                 PPropList 是指向这个数组的指针}

      num : Integer;            {记录属性的总数}
      size: Integer;            {记录属性结构的大小}
      i: Integer;        
    begin
      ClassTypeInfo := obj.ClassInfo;              {先获取: 类的信息结构指针}
      ClassDataInfo := GetTypeData(ClassTypeInfo); {再获取: 类的数据结构指针}
      num := ClassDataInfo.PropCount;              {属性总数}
      size := SizeOf(TPropInfo);                   {属性结构大小}

      GetMem(propertyList, size*num);              {给属性数组分配内存}

      GetPropInfos(ClassTypeInfo, propertyList);   {获取属性列表}

      for i := 0 to num - 1 do
      begin
        if propertyList[i].PropType^.Kind = tkMethod then {如果是事件; 事件也是属性吗, 给分出来}
          eList.Add(propertyList[i].Name)
        else
          pList.Add(propertyList[i].Name);
      end;

      pList.Sort; eList.Sort; {排序}

      FreeMem(propertyList); {释放属性数组的内存}

      Result := True;
    end;


    //测试
    procedure TForm1.Button1Click(Sender: TObject);
    var
      PL,EL: TStringList;
    begin
      PL := TStringList.Create;
      EL := TStringList.Create;

      Memo1.Clear;
      Memo2.Clear;

      GetPropertyAndEventList(Self, PL, EL); {调用函数, 第一个参数是对象名}
      Memo1.Lines := PL;
      Memo2.Lines := EL;

      PL.Free;
      EL.Free;
    end;

    end.

  • 相关阅读:
    3.18日
    线程的面试题
    关于instanceof测试遇到的问题
    spring
    自动登录代码
    Filter
    多态
    基于HTML,css,jQuery,JavaScript,MySQL搭建博客系统
    基于bootstrap+MySQL搭建动态网站
    基于bootstrap_网站汇总页面
  • 原文地址:https://www.cnblogs.com/hnxxcxg/p/2940830.html
Copyright © 2020-2023  润新知