How to access a variable by its name(string)?

拈花ヽ惹草 提交于 2019-12-17 16:47:16

问题


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!


回答1:


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.



回答2:


You could also have a global TStringList variable holding a list of name-value pairs.




回答3:


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.



来源:https://stackoverflow.com/questions/6730405/how-to-access-a-variable-by-its-namestring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!