gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:50:33 52 4
gpt4 key购买 nike

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

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

如何轻松实现这一目标?

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

谢谢!

最佳答案

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

关于delphi - 如何通过名称(字符串)访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6730405/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com