在delphi中怎么表示和使用静态的变量?
来源:http://topic.csdn.net/t/20031211/14/2552688.html
答:在Delphi5中直接用const来定义静态局部变量,在Delphi6中则可以使用const和{$J+}开关来办到。但是这样的静态变量如果定义在类方法中,那么这个类所创建的对象里的静态变量都是共享的。
我写了一个简单的例程如下:
在Delphi里New-> Application,再New-> Unit,贴入MyObj类的代码如下:
unit Unit2;
interface
type
TMyObj = class
public
procedure ShowID;
end;
implementation
uses Dialogs, SysUtils;
procedure TMyObj.ShowID;
{$J+}
const
I: Integer = 0;
{$J-}
begin
ShowMessage(IntToStr(I));
Inc(I);
end;
end.
然后回到Unit1,在Interface段添加对Unit2的引用,在Form1上放2个Button。
为Form1的OnCreate、OnClose事件以及两个Button的OnClick事件添写处理代码,最终使Unit1的代码变成如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Unit2;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
OBJ1, OBJ2: TMyObj;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
OBJ1 := TMyObj.Create;
OBJ2 := TMyObj.Create;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
OBJ1.ShowID;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
OBJ2.ShowID;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
OBJ1.Free;
OBJ2.Free;
end;
end.
现在按F9运行程序,点击Button1-> 显示数字0-> 点击Button1-> 显示数字1-> 点击Button2-> 显示数字2,这表示OBJ1和OBJ2的静态局部变量I在整个类中是共享的。