unit Unit1;interfaceuses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type test=class public class function SetData():integer; end ; TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end;var Form1: TForm1;implementation var temp:integer; {$R *.DFM}class function test.SetData: integer; begin temp:=9; temp:=temp+2; result:=temp; end;procedure TForm1.Button1Click(Sender: TObject); begin edit1.Text:=inttostr(test.SetData); end;end. edit1显示类方法SetData执行后的值
只能访问类方法,无法访问其他成员的方法 以Class开头的方法就是类方法
xite ,delphi应该禁止这种用法
除非那个类中有静态数据,例如: TStaticVar = class class FUNCTION data(const NewValue:string;Const Change:boolean):STRING; end;class function TStaticVar.data(const NewValue:string;Const Change:boolean):string; const {$J+} s:string='StaticVar';{$J-} begin if change then s:=newvalue; RESULT:=S; end;
Delphi可以,你不行,俺也不行。因为Delphi和Object Pascal中根本没有提供。
如果类中的方法不引用到类的成员变量的时候,是可以直接使用的。 例如: type TUnknown = class public procedure HelloWorld; // begin ShowMessage('Hello, World!'); end;procedure Test; var u: TUnknown; begin u.HelloWorld; // Delphi内部会把它变成HelloWorld(u)的形式 // 如果HelloWorld用到类的成员变量的话,就会出错,因此时u为空 // 但HelloWorld并不需要访问u中的变量,所以u是否为空对它没有影响,故可正常调用 end;
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;type
test=class
public
class function SetData():integer;
end ; TForm1 = class(TForm)
Button1: TButton;
Edit1: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;var
Form1: TForm1;implementation
var
temp:integer;
{$R *.DFM}class function test.SetData: integer;
begin
temp:=9;
temp:=temp+2;
result:=temp;
end;procedure TForm1.Button1Click(Sender: TObject);
begin
edit1.Text:=inttostr(test.SetData);
end;end.
edit1显示类方法SetData执行后的值
以Class开头的方法就是类方法
class FUNCTION data(const NewValue:string;Const Change:boolean):STRING;
end;class function TStaticVar.data(const NewValue:string;Const Change:boolean):string;
const
{$J+} s:string='StaticVar';{$J-}
begin
if change then
s:=newvalue;
RESULT:=S;
end;
例如:
type
TUnknown = class
public
procedure HelloWorld; // begin ShowMessage('Hello, World!');
end;procedure Test;
var
u: TUnknown;
begin
u.HelloWorld;
// Delphi内部会把它变成HelloWorld(u)的形式
// 如果HelloWorld用到类的成员变量的话,就会出错,因此时u为空
// 但HelloWorld并不需要访问u中的变量,所以u是否为空对它没有影响,故可正常调用
end;