如何通过名称(字符串)访问变量?

Joh*_*ohn 6 delphi rtti

我有一些全局字符串变量.

我必须创建我可以传递的函数并将它们存储在某个结构中.后来我需要枚举它们并检查它们的值.

如何轻松实现这一目标?

(我想我需要某种反射,或存储指针数组).无论如何,任何帮助将不胜感激.

谢谢!

Cos*_*und 7

首先,您不能将Delphi的RTTI用于此目的,因为Delphi 7的RTTI仅涵盖已发布的类成员.即使您使用的是Delphi XE,仍然没有全局变量的RTTI(因为RTTI与类型绑定,而不是"单位").

唯一可行的解​​决方案是创建自己的变量注册表,并使用名称和指向var本身的指针注册您的全局变量.

例:

unit Test;

interface

var SomeGlobal: Integer;
    SomeOtherGlobal: string;

implementation
begin
  RegisterGlobal('SomeGlobal', SomeGlobal);
  RegisterGlobal('SomeOtherGlobal', SomeOtherGlobal);
end.
Run Code Online (Sandbox Code Playgroud)

是否需要在某处定义RegisterXXX类型,可能在自己的单元中,如下所示:

unit GlobalsRegistrar;

interface

procedure RegisterGlobal(const VarName: string; var V: Integer); overload;
procedure RegisterGlobal(const VarName: string; var V: String); overload;
// other RegisterXXX routines

procedure SetGlobal(const VarName: string; const Value: Integer); overload;
procedure SetGlobal(const VarName:string; const Value:string); overload;
// other SetGlobal variants

function GetGlobalInteger(const VarName: string): Integer;    
function GetGlobalString(const VarName:string): string;
// other GetGlobal variants

implementation

// ....

end.
Run Code Online (Sandbox Code Playgroud)


Ond*_*lle 7

您还可以拥有一个TStringList包含名称 - 值对列表的全局变量.