一般来说, 编译型语言在运行时是不存在变量地址的映射表的, 但是Delphi的RTTI里面
是拥有这些信息的, 你可以通过RTTI来访问变量的名称类型以及值等信息. 具体你可以
参考:
unit MainFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TMainForm = class(TForm)
lbSamps: TListBox;
memInfo: TMemo;
procedure FormCreate(Sender: TObject);
procedure lbSampsClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses TypInfo, Buttons;
{$R *.DFM}
procedure TMainForm.FormCreate(Sender: TObject);
begin
// Add some example enumerated types
with lbSamps.Items do
begin
AddObject('TButtonState', TypeInfo(TButtonState));
AddObject('TFormStyle', TypeInfo(TFormStyle));
AddObject('Boolean', TypeInfo(Boolean));
end;
end;
procedure TMainForm.lbSampsClick(Sender: TObject);
var
OrdTypeInfo: PTypeInfo;
OrdTypeData: PTypeData;
TypeNameStr: String;
TypeKindStr: String;
MinVal, MaxVal: Integer;
i: integer;
begin
memInfo.Lines.Clear;
with lbSamps do
begin
// Get the TTypeInfo pointer
OrdTypeInfo := PTypeInfo(Items.Objects[ItemIndex]);
// Get the TTypeData pointer
OrdTypeData := GetTypeData(OrdTypeInfo);
// Get the type name string
TypeNameStr := OrdTypeInfo.Name;
// Get the type kind string
TypeKindStr := GetEnumName(TypeInfo(TTypeKind), Integer(OrdTypeInfo^.Kind));
// Get the minimum and maximum values for the type
MinVal := OrdTypeData^.MinValue;
MaxVal := OrdTypeData^.MaxValue;
// Add the information to the memo
with memInfo.Lines do
begin
Add('Type Name: '+TypeNameStr);
Add('Type Kind: '+TypeKindStr);
Add('Min Val: '+IntToStr(MinVal));
Add('Max Val: '+IntToStr(MaxVal));
// Show the values and names of the enumerated types
if OrdTypeInfo^.Kind = tkEnumeration then
for i := MinVal to MaxVal do
Add(Format(' Value: %d Name: %s', [i, GetEnumName(OrdTypeInfo, i)]));
end;
end;
end;
end.