zoukankan      html  css  js  c++  java
  • Delphi 的接口(3) 关于接口的释放


    代码文件:

    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.
    
  • 相关阅读:
    魅族Java面经
    笔试常考的Java基础
    笔试常考的Linux命令大全
    Spring概念
    Java三大框架的配置
    Myeclipse的使用
    项目经验
    Android四大组件及activity的四大启动模式
    java基础
    IT在线笔试总结(二)
  • 原文地址:https://www.cnblogs.com/del/p/1496742.html
Copyright © 2011-2022 走看看