分享

Delphi类的入门例子(9): 获取对象的 RTTI 属性与事件的函数

 quasiceo 2017-03-03

Delphi类的入门例子(9): 获取对象的 RTTI 属性与事件的函数

时间:2011-12-12 万一

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.

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多