English 中文(简体)
在运行时获取一个类中的变量名列表
原标题:Get list of variable names in a class at run time
  • 时间:2012-05-23 04:43:27
  •  标签:
  • delphi

我宣布在节目中开设一些简单的课程,例如:

MyClass = class 
    Var1 : Integer
    Var2 : Integer
end;

我想做的是获取一个列表, 列出在运行时该类的变量 (“ MyClass” ) (可能有些像“ GetPropList ” 的组件? ) 。

我有类似的想法(显然,“ GetVarNames” 函数不存在, 但我希望这能给出这个想法),

var
    MyVariableNamesList: TStringList
    i : integer;

begin
    MyVariableNamesList := TStringList.create;        
    MyVariableNamesList := GetVarNames(MyClass)

end;

如果这是愚蠢的问题,请事先道歉!

问题回答

根据您的 Delphi 版本, 您可以使用新的 RTTI (与 Delphi 2010 一起推出) 。

你可以做这样的事:

function GetVarNames(const AClass : TObject) : TStringList;
var lType : TRttiType;
  lContext : TRttiContext;
  lProperty : TRttiProperty;
  lField : TRttiField;
begin
  Result := TStringList.create;
  LType := lContext.GetType(AClass.ClassType);
  if assigned(LType) then
  begin
    for LProperty in LType.GetProperties do
    begin
      Result.Add(lProperty.Name);
      //Get current value:
      Result.Add(lProperty.GetValue(AClass).ToString);
    end;
   for lField in LType.GetFields do
   begin
     Result.Add(lField.Name);
     //Get current value:
     Result.Add(lField.GetValue(AClass).ToString);
   end;
 end;
end;




相关问题
determining the character set to use

my delphi 2009 app has a basic translation system that uses GNUGetText. i had used some win API calls to prepare the fonts. i thought it was working correctly until recently when someone from Malta ...

Help with strange Delphi 5 IDE problems

Ok, I m going nuts here. For the last (almost) four years, I ve been putting up with some extremely bad behavior from my Delphi 5 IDE. Problems include: Seemingly random errors in coride50.bpl ...

How to write a Remote DataModule to run on a linux server?

i would like to know if there are any solution to do this. Does anyone? The big picture: I want to access data over the web, using my delphi thin clients. But i´would like to keep my server/service ...

How convert string to integer in Oxygene

In Delphi, there is a function StrToInt() that converts a string to an integer value; there is also IntToStr(), which does the reverse. These functions doesn t appear to be part of Oxygene, and I can ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签