如何通过名称(字符串)访问变量?
我有一些全局字符串变量。
我必须创建我可以传递的函数 &将它们存储在某种结构中。 稍后我需要枚举它们并检查它们的值。
如何才能轻松实现这一目标?
(我想我需要某种反射,或者存储指针数组)。 无论如何,任何帮助将不胜感激。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您不能使用 Delphi 的 RTTI 来实现此目的,因为 Delphi 7 的 RTTI 仅涵盖已发布的类成员。即使您使用的是 Delphi XE,全局变量仍然没有 RTTI(因为 RTTI 与类型相关,而不是与“单位”相关)。
唯一可行的解决方案是创建您自己的变量注册表并使用名称和指向 var 本身的指针来注册全局变量。
示例:
RegisterXXX 类型是否需要在某处定义,可能在自己的单元中,如下所示:
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:
were the RegisterXXX types would need to be defined somewhere, probably in there own unit, like this:
您还可以有一个全局
TStringList
变量,其中包含名称-值对列表。You could also have a global
TStringList
variable holding a list of name-value pairs.在 Delphi 7 上,我会遵循 Cosmin 的接口想法,而对于实现,我会使用基于 Julian Bucknall 的 Delphi 优秀数据结构代码的字典类型, ezDSL。
delphi 的更高版本(例如 XE)不仅具有更高级的 RTTI,它们还包含一个非常好的字典类型,使用泛型,因此字典可以包含您喜欢的任何类型。 esDSL 字典非常容易使用,但由于它是基于指针的,因此它不像 delphi 泛型字典那样类型安全。
由于您需要做的是在非常快的时间内查找字符串“变量名称”(我们喜欢称之为 O(1)),因此您需要的是一个字符串到变量的字典。您可以使用字符串作为键,使用变体作为字典中的值,然后删除原始的全局变量,或者您可以尝试一些相当复杂的全局指针逻辑,但我真的认为您会更好使用
键、值元组的简单字典。On Delphi 7, I would follow Cosmin's idea for the interface, and for the implementation, I would use a dictionary type based on Julian Bucknall's excellent data structures code for Delphi, ezDSL.
Later versions of delphi like XE not only have more advanced RTTI they also include a pretty great dictionary type, using generics, so the dictionary can contain any type you like. The esDSL dictionary is pretty easy to use but since it's pointer based, it isnt as type safe as the delphi generics dictionary.
Since what you need to do is look up string "variable names" in very fast time (O(1) we like to call it), what you need is a string-to-variable dictionary. You could have Strings for the keys, and Variants as the values in the dictionary, and just get rid of the original global variables, or you could attempt some rather complex pointers-to-globals logic, but I really think you'd be better off with a simple dictionary of
<string,variant>
key,value tuples.