(2)类方法和普通方法的区别

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

{定义类}
  TMyForm = class
    public
    class procedure Show; //类方法
    procedure Show1;      //普通方法
    constructor Create;    //Constructor 构造函数,如果不写这个也不会出什么错,加上目的是为了在类被创建的时候执行一些初始化
    destructor Desttroy;  //Destructor  析构函数,这个也可以不写。加上的目的是为了在类销毁的时候进行一些资源的释放
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TMyForm }

constructor TMyForm.Create; //Create也属于类方法
begin
  Show; //内部调用类方法,即在TMyForm创建的时候将ShowMessage('这是一个类方法');
end;

destructor TMyForm.Desttroy;
begin
  Show;  //内部调用类方法,即在TMyForm销毁的时候将ShowMessage('这是一个类方法');
end;

class procedure TMyForm.Show;
begin
  ShowMessage('这是类方法');
end;

procedure TMyForm.Show1;
begin
  ShowMessage('这是普通方法');
end;


procedure TForm1.Button1Click(Sender: TObject);
begin
  TMyForm.Show;  //使用类方法不用创建对象可以直接使用
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  My : TMyForm;      //创建一个TMyForm的对象 My
begin
  My := TMyForm.Create;  //调用Create构造方法创建 My.
  My.Show1;              //调用TMyFomr中这个普通方法
  My.Desttroy;           //调用Desttroy析构方法释放 My
end;
end.

以上代码执行下来会发现点击button1的时候会出现 '这是一个类方法' ,而点击button2的时候会依次出现 '这是一个类方法''这是一个普通方法' , '这是一个类方法'。这是因为在TMyForm的构造函数中执行了类方法,析构函数又执行了类方法,所以,加上本来那句My.Show1就会依次出现三条文本了。  而这也是构造函数和析构函数的好处,能对程序进行一些初始化与资源释放等等操作。

原文地址:https://www.cnblogs.com/mdnx/p/2573726.html