作用域表示变量在程序不同部分的可视度。下面给出了一个完整代码例子,例子中包括了三个作用域中的相同名称的变量X。
Step1、新建一个Application,并在Form1上面放置一个Memo控件(memo1)和Button控件(button1)。
Step2、添加代码,完成后,完整的Unit1单元如下显示:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
var
X: Integer; {Unit variable X }
{
implementation中声明的变量在整个单元中都是可见的
}
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
X: Integer;
{
在Button1Click中声明的变量只在此过程中有效
}
procedure Test;
var
X: Integer;
{
在Test过程声明的变量只在此局部过程中有效
}
begin
X := 300;
{ This X variable has value of 300}
memo1.Lines.Add('Local Function X = ' + IntToStr(X));
end;
begin
Memo1.Lines.Clear;
{ Local X has a value of 100.}
X := 100;
Memo1.Lines.Add('Local X = ' + inttostr(X));
Memo1.Lines.Add('Global X = ' + IntToStr(Unit1.X));
{ Call the Test procedure}
Test;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
{ Initialize the Unit variable X.}
X := 200;
end;
end.
如上面的例子,在Button1Click过程内部还实现了一个Test子过程,而此子过程的作用域只能被父过程调用。如果一个过程中有多个子过程,那么实现位置更靠后的子过程可以调用它前面的子过程。
Note
真正的全局变量对程序的任何单元都是有效的,而不要把包含此变量的单元添加到uses列表中。Delphi有几个全局变量,它们由编译器的启动代码设置。一般程序员不能自己声明真正的全局变量。
以上代码均在Delphi7中测试通过。