Delphi class static properties

zhaozj2021-02-08  254

Because Delphi not provide static member for our using, so if you want a static member of class in Delphi what should I do? Ok! At least there are three ways to implement this.1, Using private global variant (in implement section of unit ), But there is a lit

Visibility Scope in Project Or Unit.2, USING GLOBAL VARIANT, A More Visibility Scope in Project Or Unit.a Lit Same AS

Above.3, Using Typed Constant, Just Using Compiler Directive $ J or Project Properties

Compiler Option Typed Constant.There Area Some Simple Source Code As Follows:

Unit unit1;

Interface

Uses Windows, Messages, Sysutils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Stdctrls;

TYPE TFORM1 = Class (TFORM) Button1: TButton; Procedure Button1Click (sender: TOBJECT); private {private declarations} end;

TStaticMemberObject = class private class procedure SetName (const Value: string); class function GetName: string; class function StaticMethod (ReadFlag: boolean; var Value: string): boolean; published property Name: string read GetName write SetName; end;

Var Form1: TFORM1;

IMPLEMENTATION

{$ R * .dfm}

{TSTATICMEMBEROBJECT}

class function TStaticMemberObject.StaticMethod (ReadFlag: boolean; var Value: string): boolean; const static: string = ''; begin result: = True; if ReadFlag then Value: = static else static: = value; end;

Class function tstaticmemberObject.getname: string; var value: string; begin staticmethod (true, value); result: = value;

Class procedure tstaticmemberObject.setname (const value: string); var setValue: string; begin setValue: = value; staticmethod (false, setvalue);

procedure TForm1.Button1Click (Sender: TObject); var so: TStaticMemberObject; begin so.Name: '! Hello, my static property' =; ShowMessage (so.Name); so.SetName ( 'hi, my static property!') ShowMessage (SO.GETNAME); END;

Please pay attention to the class method used here. The name Property's Modifiers

Both Use Class Method. in Fact if you Use Normal Static Method with no class

Directive The Code Still Works Work. Like this: Procedure SetName (const value: string); Function GetName: String; Because We Do Not Access Other Fields and Other Instance Methods of this

TSTATICMEMBEROBJECT CLASS or Some Object of TStaticMemberObject Type, So There IS

NO av us Normal static method.ok, if you need this trick job.

转载请注明原文地址:https://www.9cbs.com/read-1866.html

New Post(0)