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.

posted on 2008-01-14 02:25  万一  阅读(6203)  评论(3编辑  收藏  举报