方法主要分为过程和函数
有返回值的方法是函数,没有返回值的方法是过程
在类中有两个区域可以声明方法
TMyClass = class(TComponent)
private//这里
{ private declarations }
protected
{ protected declarations }
public//这里
{ public declarations }
published
{ published declarations }
end;
在私有区声明的方法只有本单元内可以使用
公共区声明的方法可供其他单元调用
在这里举一个例子
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyClass = class
private
{ private declarations }
protected
{ protected declarations }
public
{ public declarations }
procedure Mypro;
function Myfun(i: Integer): Integer;
published
{ published declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyClass }
function TMyClass.Myfun(i: Integer): Integer;
begin
i := i * 2;
Result := i;
end;
procedure TMyClass.Mypro;
begin
ShowMessage('s.y你好');
end;
procedure TForm1.btn1Click(Sender: TObject);
var
i: Integer;
myclass: TMyClass;
begin
myclass := TMyClass.Create;
i := 6;
myclass.Mypro; // sy你好
i := myclass.Myfun(i);
ShowMessage(IntToStr(i)); // 12
end;
end.