微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我必须创建我可以通过的功能&将它们存放在某种结构中.
后来我需要枚举它们并检查它们的值.

如何轻松实现这一目标?

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

谢谢!

解决方法

首先,您不能将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.

是否需要在某处定义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.

原文地址:https://www.jb51.cc/delphi/101667.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐