简体   繁体   中英

Delphi global variable setter

I got problem with setting global variable in Delphi unit:

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

procedure TSomeForm.SetNewVersion(variable1: String);
begin

    variable1 := variable1; //here is problem

end;

How to assign value to global variable if it have same name like local argument value from procedure? If that is some form value, that can be done like this:

TSomeForm.variable1 = variable1;

But problem is when variable is global variable in unit?

SomeUnit.variable1 = variable1; // this dont work

FWIW: The following works as one might expect:

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;

To avoid such problems you might consider prefixing arguments with 'A' which is kind of semi-standard in Delphi. And while you're at it, make string parameters const :

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

You can solve your problem by either:

  • Choosing a different name for the parameter (or indeed the global variable). Personally I tend to use the name Value for the parameter of a setter method. Or,
  • Fully qualifying the name like this SomeUnit.variable1 .

Note that the assignment operator is := and not = .

I would strongly recommend that you reconsider the design.

Should the variable really be global? If it is associated with a form instance as is implied by your setter, shouldn't it be a private member variable of the form class.

If the variable really is shared between instances, make the variable a private class variable and the setter a class method.

If your Delphi does not have class variables then move the global variable into the implementation section. As your code stands, there's no point in having a setter because you also expose the backing variable in the interface section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM