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.
    
  • 相关阅读:
    数学思想方法-python计算战(8)-机器视觉-二值化
    04-05组合问题_算法训练
    至HDFS附加内容
    HDU 1010 Tempter of the Bone heuristic 修剪
    二叉树3种遍历的非递归算法
    [Ramda] R.project -- Select a Subset of Properties from a Collection of Objects in Ramda
    [Ramda] Refactor a Promise Chain to Function Composition using Ramda
    [SVG] Combine Multiple SVGs into an SVG Sprite
    [Ramda] Difference between R.converge and R.useWith
    [Ramda] Refactor to a Point Free Function with Ramda's useWith Function
  • 原文地址:https://www.cnblogs.com/del/p/1037556.html
Copyright © 2011-2022 走看看