如何枚举对象中的所有属性并获取它们的值? [英] How do I enumerate all properties in an object and obtain their values?

查看:489
本文介绍了如何枚举对象中的所有属性并获取它们的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想枚举所有属性:私有,受保护,公共等。我希望使用内置功能,而不使用任何第三方代码。

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;

这篇关于如何枚举对象中的所有属性并获取它们的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆