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.