Rtti访问私有变量小记

对rtti访问私有变量的一个demo

 

直接上代码!

 

  1 unit Unit1;
2
3
4
5 interface
6
7
8
9 uses
10
11 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
12
13 Dialogs, Rtti, StdCtrls;
14
15
16
17 type
18
19 TForm1 = class(TForm)
20
21 Btn1: TButton;
22
23 Edit1: TEdit;
24
25 procedure Btn1Click(Sender: TObject);
26
27 private
28
29 { Private declarations }
30
31 FList: TList;
32
33 public
34
35 { Public declarations }
36
37 end;
38
39
40
41 var
42
43 Form1: TForm1;
44
45
46
47 implementation
48
49
50
51 {$R *.dfm}
52
53
54
55 procedure TForm1.Btn1Click(Sender: TObject);
56
57 var
58
59 rttiContext : TRttiContext;
60
61 rtype : TRttiType;
62
63 rField : TRttiField;
64
65 rV: TValue;
66
67 SName: string;
68
69 I: Integer;
70
71 vCom: TComponent;
72
73 begin
74
75 FList := TList.Create;
76
77 rttiContext := TRttiContext.Create;
78
79 rtype := rttiContext.GetType(TForm1);
80
81 rField := rType.GetField('FComponents');
82
83 if rField <> nil then
84
85 begin
86
87 rV := rField.GetValue(Self);
88
89 if rV.IsType<TList> then
90
91 begin
92
93 FList.Add(TValuedata(rV).FAsPointer);
94
95 end;
96
97 end;
98
99 for I := 0 to TList(FList[0]).Count - 1 do
100
101 begin
102
103 vCom := TList(FList[0])[i];
104
105 SName := SName + vCom.Name + ';';
106
107 end;
108
109 ShowMessage(Format('FListCount:%d FList[1].Count:%d CompName:%s',[FList.Count,TList(FList[0]).Count,SName]));
110
111 FreeAndNil(FList);
112
113 rttiContext.Free;
114
115 end;
116
117
118
119 end.



posted @ 2011-10-13 23:27  血舞&葬青衣  Views(404)  Comments(1Edit  收藏  举报