如何枚举对象中的所有属性并获取它们的值?
问题描述:
我想枚举所有属性:私有,受保护,公共等。我希望使用内置功能,而不使用任何第三方代码。
I want to enumerate all properties: private, protected, public etc. I wish to use the built in facilities and not use any third party code.
答
使用像这样的扩展RTTI(当我在XE中测试代码时,ComObject属性出现异常,因此我插入了try-除了块):
Use Extended RTTI like this (when I tested the code in XE I got exception on ComObject property, so I inserted try - except block):
uses RTTI;
procedure TForm1.Button1Click(Sender: TObject);
var
C: TRttiContext;
T: TRttiType;
F: TRttiField;
P: TRttiProperty;
S: string;
begin
T:= C.GetType(TButton);
Memo1.Lines.Add('---- Fields -----');
for F in T.GetFields do begin
S:= F.ToString + ' : ' + F.GetValue(Button1).ToString;
Memo1.Lines.Add(S);
end;
Memo1.Lines.Add('---- Properties -----');
for P in T.GetProperties do begin
try
S:= P.ToString;
S:= S + ' : ' + P.GetValue(Button1).ToString;
Memo1.Lines.Add(S);
except
ShowMessage(S);
end;
end;
end;