delphi全局变量的定义与赋值主要有下面几种方法:
1.
全局变量的初始化
在最后结束的end.之前,增加initialization关键字,然后加入对全局变量的初始化,这样就可以初始化全局变量了.不论在interface还是在implementation部分的全部变量,都可以这么来初始化
//省略前面的interface, uses, type.
var
i: Integer;
implementation
var
j: Integer;
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
Inc(i);
Inc(j);
Form1.Caption := IntToStr(i) + ‘ ‘ + IntToStr(j);
end;
initialization
i := 100;
j := 200;
end.
2. 新建一个公用单元,专门放置公用全局变量呗
unit untCommon;
interface
var
v1:integer;
v2:string;
end.
-----------------
unit unit1;
interface
uses
windows, ................, untCommon ; //在每个需要使用v1、v2变量的单元中引用上面那个单元untCommon就可以了
3.跟 一般变量赋值差不多!
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
/////////////////////////////
//在 implementation上定义的全局变量在所有单元可见
var teststr:string;
implementation
{$R *.dfm}
//////////////////////////////
//在implementation下定义的只对本单元可见
var teststr1:string;
procedure TForm1.Button1Click(Sender: TObject);
begin
//////////////////////
//对teststr赋值
teststr := ‘我是对所有单元都可见的‘;
showmessage(teststr);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
/////////////////////
//对teststr11赋值
teststr1 := ‘我只对本单元可见‘;
showmessage(teststr1);
end;
end.