|
Delphi实现静态变量
<div id="cnblogs_post_body">C++有静态变量,static关键字描述,其实Delphi也可以做到。
以前一般采用的是const方法来实现,现在的Delphi可以用class关键字来实现。
附代码如下,两种方式具有示例。
<div class="cnblogs_code"> 1 unit Unit6; 2 3 interface 4 5 uses 6 Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, 7 Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; 8 9 type10 TTestClass = class11 private12 {$J+}13 const FTest : integer = 0;14 {$J-}15 class var FTest2 : integer;16 function GetTest: integer;17 function GetTest2: integer;18 public19 constructor Create;virtual;20 21 property Test : integer read GetTest;22 property Test2 : integer read GetTest2;23 end;24 25 TForm6 = class(TForm)26 Button1: TButton;27 procedure Button1Click(Sender: TObject);28 private29 { Private declarations }30 public31 { Public declarations }32 end;33 34 var35 Form6: TForm6;36 37 implementation38 39 {$R *.dfm}40 41 { TTestClass }42 43 constructor TTestClass.Create;44 begin45 Inc(FTest);46 Inc(FTest2);47 end;48 49 function TTestClass.GetTest: integer;50 begin51 Result := FTest;52 end;53 54 function TTestClass.GetTest2: integer;55 begin56 Result := FTest2;57 end;58 59 procedure TForm6.Button1Click(Sender: TObject);60 var61 ATest : TTestClass;62 begin63 ATest := TTestClass.Create;64 Caption := IntToStr(ATest.GetTest)+':'+IntToStr(ATest.GetTest2);65 end;66 67 end. |
|