程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> Delphi的接口(3) - 關於接口的釋放

Delphi的接口(3) - 關於接口的釋放

編輯:Delphi

代碼文件:

unit Unit1;

interface

uses
 Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
 Dialogs, StdCtrls;

type
 TForm1 = class(TForm)
  Button1: TButton;
  Button2: TButton;
  Button3: TButton;
  Button4: TButton;
  procedure Button1Click(Sender: TObject);
  procedure Button2Click(Sender: TObject);
  procedure Button3Click(Sender: TObject);
  procedure Button4Click(Sender: TObject);
 end;

 IMyInterface = interface
  procedure Proc;
 end;

 TMyClass = class(TInterfacedObject, IMyInterface)
 public
  constructor Create;
  destructor Destroy; override;
  procedure Proc;
 end;

var
 Form1: TForm1;

implementation

{$R *.dfm}

constructor TMyClass.Create;
begin
 inherited;
 ShowMessage('TMyClass.Create');
end;

destructor TMyClass.Destroy;
begin
 ShowMessage('TMyClass.Destroy');
 inherited;
end;

procedure TMyClass.Proc;
begin
 ShowMessage('IMyInterface.Proc');
end;

procedure TForm1.Button1Click(Sender: TObject);
var
 c: TMyClass;
begin
 c := TMyClass.Create;
 c.Proc;
 c.Free;
 ShowMessage('**********');

{將依次顯示:
  TMyClass.Create
  IMyInterface.Proc
  TMyClass.Destroy
  **********
}
end;

procedure TForm1.Button2Click(Sender: TObject);
var
 i: IMyInterface;
begin
 i := TMyClass.Create;
 i.Proc;
 ShowMessage('**********');
 //在本段程序的最後, 編譯器能判斷出接口不再有用, 會釋放掉擁有它的類

{將依次顯示:
  TMyClass.Create
  IMyInterface.Proc
  **********
  TMyClass.Destroy
}
end;

procedure TForm1.Button3Click(Sender: TObject);
var
 c: TMyClass;
 i: IMyInterface;
begin
 c := TMyClass.Create;
 i := c;
 //i := IMyInterface(c);  {也可以這樣轉換}
 //i := c as IMyInterface; {暫時不能使用 as, 接口擁有 GUID 後才可以使用 as 轉換}
 i.Proc;
 ShowMessage('**********');

{將依次顯示:
  TMyClass.Create
  IMyInterface.Proc
  **********
  TMyClass.Destroy
}
end;

procedure TForm1.Button4Click(Sender: TObject);
var
 i: IMyInterface;
begin
 i := TMyClass.Create;
 i.Proc;
 i := nil; //可以這樣主動釋放接口; 同時擁有它的類也會釋放
 ShowMessage('**********');

{將依次顯示:
  TMyClass.Create
  IMyInterface.Proc
  TMyClass.Destroy
  **********
}
end;

end.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved