【www.arisingsemi.com--热门资讯】

方式和方法的区别
Delphi有的方法在前面都加上了Class关键字,即方法被声明为类方法。类方法与普通方法不同,普通方法只有在对象被实例化后才可调用,否则会因为对象未被创建而引发异常,这种异常所表现出的特征往往是莫名其妙的。如果跟踪程序就会发现,这种因对象为实例化而造成的异常往往是在调用对象的方法时引发访问无效内存的提示,并有可能造成死机等;并且在出错时很难被发现,因为程序的逻辑是正确的。而类方法的调用却不需要对象的实例化,即对象被声明后就可以调用类方法,因此类方法的编写有一定的约束,即不能访问类所声明的变量。因为类未实例化,变量的存储空间还未分配。
示例
1:
//类声明
TMyClass = class
public
class procedure MyProc;  //类方式
constructor Create;      //Create 也是类方法
end;
var
Form
1: TForm1;
implementation
{$$R *.dfm}
{ TMyClass }
constructor
begin
inherited;
MyProc;  //内部调用类方法
end;
class procedure
begin
ShowMessage("ok");  //类方法实现
end;
procedure eate(Sender: TObject);
var
MyClass
1: TMyClass;
begin
;  //用类名调用类方法,显示:ok  只有类方法才能 直接用类 调用
MyClass1 :=   //内部调用类方法,显示:ok      构造                             
;  //对象调用类方法,显示:ok      类方法 也可以用 对象 调用
;
end;
示例2(私有 公有):
unit Unit2;
interface
uses
Windows, Forms, Dialogs;
type
TA = class
private
class procedure aa;
public
class procedure bb;
procedure cc;
end;
implementation
class procedure
begin
showmessage("aa");
end;
class procedure
begin
showmessage("bb");
end;
procedure
begin
showmessage("cc");
end;
end.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Unit2, StdCtrls;
type
TForm1 = class(TForm)
Button
1: TButton;
Button
2: TButton;
Button
3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form
1: TForm1;
implementation
{$$R *.dfm}
procedure 1Click(Sender: TObject);
begin
;  //编译通过
end;
procedure 2Click(Sender: TObject);
begin
;//编译通不过
end;
procedure 3Click(Sender: TObject);
Var
TA
1:TA;
begin
;//编译通过
end;
procedure 3Click(Sender: TObject);
//Var
//TA
1:TA;
begin
;//编译不通过
end;
end.-
网站统计 。

本文来源:http://www.arisingsemi.com/news/139393/