zoukankan      html  css  js  c++  java
  • 关于类的入门例子(9): 获取对象的 RTTI 属性与事件的函数

    unit Unit1;
    
    interface
    
    uses
      Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
      Dialogs, StdCtrls, xmldom, XMLIntf, XMLBrokr, msxmldom, XMLDoc;
    
    type
      TForm1 = class(TForm)
        Button1: TButton;
        Button2: TButton;
        Memo1: TMemo;
        Memo2: TMemo;
        XMLDocument1: TXMLDocument;
        procedure Button1Click(Sender: TObject);
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.dfm}
    
    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.
    
  • 相关阅读:
    运动会管理系统
    sql2008开发版
    wordpress改变ip或域名
    mssql技巧
    ubuntukylin ubuntu1304
    手把手玩转win8开发系列课程(13)
    手把手玩转win8开发系列课程(14)
    手把手玩转win8开发系列课程(19)
    手把手玩转win8开发系列课程(11)
    手把手玩转win8开发系列课程(17)
  • 原文地址:https://www.cnblogs.com/del/p/1037556.html
Copyright © 2011-2022 走看看