Delphi全局变量设置器

Delphi全局变量设置器,delphi,variables,global,Delphi,Variables,Global,我在Delphi单元中设置全局变量时遇到问题: unit SomeUnit; ... interface ... var variable1: String; ... implementation procedure TSomeForm.SetNewVersion(variable1: String); begin variable1 := variable1; //here is problem end; 若全局变量和过程中的局部参数值具有相同的名称,那个么如何为其赋值?如果这

我在Delphi单元中设置全局变量时遇到问题:

unit SomeUnit;
...
interface
...
var
variable1: String;
...
implementation

procedure TSomeForm.SetNewVersion(variable1: String);
begin

    variable1 := variable1; //here is problem

end;
若全局变量和过程中的局部参数值具有相同的名称,那个么如何为其赋值?如果这是某种形式的值,可以这样做:

TSomeForm.variable1 = variable1;
但问题是当变量是单位中的全局变量时

SomeUnit.variable1 = variable1; // this dont work

FWIW:正如人们所预料的那样,以下工作是有效的:

var
  SomeForm: TSomeForm;
  variable1: string;

implementation

{$R *.dfm}

{ TSomeForm }

procedure TSomeForm.FormCreate(Sender: TObject);
begin
  Assert(SomeUnit.variable1 = '');
  SetNewVersion('1');
  Assert(SomeUnit.variable1 = '1');
end;

procedure TSomeForm.SetNewVersion(variable1: string);
begin
  SomeUnit.variable1 := variable1;
end;
为了避免这些问题,你可以考虑用“A”作为前缀参数,这是Delphi中的半标准。在执行此操作时,将字符串参数设置为const:

procedure TSomeForm.SetNewVersion(const AVariable1: string);
begin
  variable1 := AVariable1;
end;

您可以通过以下任一方式解决问题:

  • 为参数(实际上是全局变量)选择不同的名称。就我个人而言,我倾向于使用名称
    Value
    作为setter方法的参数。或者
  • 完全限定名称,如下所示
    SomeUnit.variable1
请注意,赋值运算符是
:=
,而不是
=

我强烈建议你重新考虑这个设计

这个变量真的应该是全局变量吗?如果它与setter暗示的表单实例相关联,那么它不应该是表单类的私有成员变量吗

如果变量确实在实例之间共享,则将变量设为私有类变量,将setter设为类方法


如果您的Delphi没有类变量,那么将全局变量移动到实现部分。就您的代码而言,使用setter没有任何意义,因为您还可以在接口部分公开支持变量

设置全局变量没有问题。使用全局变量可能会出现问题。不要将局部变量命名为与全局变量相同的名称。将局部变量名称更改为其他名称。就这么简单。
TSomeForm.variable1=variable1;//这不起作用
——它肯定不起作用。使用
:=
分配变量,而不是代替比较符号=是错误的,我认为:=