class function或class 类函数 类过程
类函数\类过程. 它们是直接操作在类上面(没有实例化的对象)
下面是Delphi Help 的描述
A class method is a method (other than a constructor) that operates on classes instead of objects. The definition of a class method must begin with the reserved word
class. For example,
type
TFigure = class
public
class function Supports(Operation: string): Boolean; virtual;
class procedure GetInfo(var Info: TFigureInfo); virtual;
...
end;
The defining declaration of a class method must also begin with class. For example,
class procedure TFigure.GetInfo(var Info: TFigureInfo);
begin
...
end;
In the defining declaration of a class method, the identifier Self represents the class where the method is called (which could be a descendant of the class in which it is defined). If the method is called in the class C, then Self is of the type class of C. Thus you cannot use Self to access fields, properties, and normal (object) methods, but you can use it to call constructors and other class methods.
A class method can be called through a class reference or an object reference. When it is called through an object reference, the class of the object becomes the value of Self.
类方法(Class methods)是一类特殊的方法,它们在声明时要以 class 开头:
type
TFigure = class
public
...
class procedure GetInfo(var Info: TFigureInfo); virtual;
...
end;
实现时也以 class 开头:
class procedure TFigure.GetInfo(var Info: TFigureInfo);
begin
...
end;
乍一看好象平时没有遇到过这个东东,好象这个东东也没有什么大作用,其实不然。比如我们有时为输入密码或其他常用数据专门做一个 Form,但由于其代码都在 Form 定义的 unit 里面,所以在使用时仅仅需要几行代码,比如:
with TfrmPassword.Create(nil) do
try
ShowModal;
finally
Free;
end;
虽然这样的代码已经很简洁,但如果写多了还是很讨厌的。利用类方法可以使其更简洁:
TfrmPassword = class(TForm)
...
public {Public declarations }
class function Execute: TModalResult;
end;
...
class function TfrmPassword.Execute: TModalResult;
begin
with TfrmPassword.Create(nil) do
try
Result :=ShowModal;
finally
Release; //注意此处必须为release不能为free!
end;
end;
然后只用一行 TfrmPassword.Execute; 即可直接完成调用!