如何通过名称(字符串)访问变量? [英] How to access a variable by its name(string)?

查看:547
本文介绍了如何通过名称(字符串)访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我必须创建我可以通过的功能存储在一些结构。
以后我需要枚举他们并检查他们的价值。



这样怎么可以轻松实现?



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



谢谢!

解决方案>

首先,您不能为此目的使用Delphi的RTTI,因为Delphi 7的RTTI仅涵盖已发布的课程成员。即使您使用的是Delphi XE,全局变量仍然没有RTTI(因为RTTI与单位不一致)。



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



示例:



单元测试

  

接口

var SomeGlobal:Integer;
SomeOtherGlobal:string;

实现
begin
RegisterGlobal('SomeGlobal',SomeGlobal);
RegisterGlobal('SomeOtherGlobal',SomeOtherGlobal);
结束。 RegisterXXX类型需要在某个地方进行定义,大概在这个单元中,如下所示:



  unit GlobalsRegistrar; 

接口

程序RegisterGlobal(const VarName:string; var V:Integer);超载;
程序RegisterGlobal(const VarName:string; var V:String);超载;
//其他RegisterXXX例程

过程SetGlobal(const VarName:string; const Value:Integer);超载;
procedure SetGlobal(const VarName:string; const Value:string);超载;
//其他SetGlobal变体

函数GetGlobalInteger(const VarName:string):Integer;
函数GetGlobalString(const VarName:string):string;
//其他GetGlobal变体

实现

// ....

结束。


I have some global string variables.

I have to create the function that I could pass & store them in some structure. Later I need to enumerate them and check their values.

how can this be easily achieved?

(I think I would need some kind of reflection, or store array of pointers). Anyway, any help will be appreciated.

Thanks!

解决方案

First of all you can't use Delphi's RTTI for that purpose, because Delphi 7's RTTI only covers published members of classes. Even if you were on Delphi XE, there's still no RTTI for global variables (because RTTI is tied to Types, not to "units").

The only workable solution is to create your own variable registry and register your globals using a name and a pointer to the var itself.

Example:

unit Test;

interface

var SomeGlobal: Integer;
    SomeOtherGlobal: string;

implementation
begin
  RegisterGlobal('SomeGlobal', SomeGlobal);
  RegisterGlobal('SomeOtherGlobal', SomeOtherGlobal);
end.

were the RegisterXXX types would need to be defined somewhere, probably in there own unit, like this:

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.

这篇关于如何通过名称(字符串)访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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