Delphi中实现C++/Java类似静态变量的功能

类别:编程语言 点击:0 评论:0 推荐:

在网上看到很多人都在为Delphi是否支持C++/Java中的静态变量及静态方法的功能而困扰,其实这在Delphi中是很简单的.

静态方法就是使用Class Function. 静态变量则使用单元局部变量来实现. 代码如下:

//========================================= // StaticVarTestU - 定义了可以计数的类,通过类方法即可访问此类的对象数 //========================================= unit StaticVarTestU; interface type TStaticVarClass = class public //constructor constructor Create(); destructor Destroy; override; //类方法,取得对象的计数 class function ObjectCount: integer; protected private end; implementation Var LObjCount: integer; { TStaticVarClass } constructor TStaticVarClass.Create; begin inc(LObjCount); //使用局部变量 end; destructor TStaticVarClass.Destroy; begin dec(LObjCount); //使用局部变量 inherited; end; class function TStaticVarClass.ObjectCount: integer; begin Result := LObjCount; //返回局部变量 end; initialization LObjCount := 0; //初始化 finalization LObjCount := 0; end. //========================================= // StaticTest - 测试代码,创建10个对象,并访问其计数,再Free掉. //========================================= program StaticTest; {$APPTYPE CONSOLE} uses SysUtils, Classes, StaticVarTestU in 'StaticVarTestU.pas'; procedure printObjCount; begin WriteLn(Format('The Object Count now is %d', [TStaticVarClass.ObjectCount])); end; var i: integer; mObjList: TList; begin { TODO -oUser -cConsole Main : Insert code here } mObjList := TList.Create; printObjCount; for i := 0 to 10 do begin mObjList.Add(TStaticVarClass.Create()); printObjCount; end; for i := 0 to mObjList.Count -1 do begin TStaticVarClass(mObjList.Items[i]).Free; printObjCount; end; mObjList.Free; readln; end. 请大家指正....

本文地址:http://com.8s8s.com/it/it22221.htm