I saw that many people are troubled by whether Delphi supports static variables and static methods in C / Java, in fact, this is very simple in delphi.
The static method is to use Class Function. Static variables are implemented using unit local variables. The code is as follows:
/ / ======================================================================================================================================================================
// staticvartestu - Defines the class that can be counted, access the number of objects of such objects by class methods
/ / ======================================================================================================================================================================
Unit static rourtestu;
Interface
Type
TSTATICVARCLASS = Class
public
// conncture
Constructor crete ();
DESTRUCTOR DESTROY; OVERRIDE;
// class method, obtain the number of objects
Class Function Objectcount: Integer;
protected
Private
END;
IMPLEMentation
VAR
Lobjcount: Integer;
{TSTATICVARCLASS}
Constructor TSTATICVARCLASS.CREATE;
Begin
INC (LOBJCOUNT); // use local variables
END;
Destructor TStaticVarclass.Destroy;
Begin
Dec (lobjcount); // use local variables
inherited;
END;
Class Function TStaticVarclass.Objectcount: Integer;
Begin
Result: = lobjcount; // Return local variables
END;
INITIALIZATION
Lobjcount: = 0; // Initialization
Finalization
LOBJCOUNT: = 0;
End.
/ / ======================================================================================================================================================================
// statictest - Test code, create 10 objects and access their count, and then FREE.
/ / ======================================================================================================================================================================
Program statictest;
{$ Appype 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]).
PrintObjcount;
END;
Mobjlist.free;
READLN;
End.
Please refer to you.