zoukankan      html  css  js  c++  java
  • 07.Delphi接口的生命周期

    在Delphi的接口中,是不需要释放的,调用完之后,接口的生命周期就结束了,如下面的例子

    unit mtReaper;
    
    interface
    
    type
      // 定义一个接口
      IBase = interface
        ['{F3E97960-3F35-11D7-B847-001060806215}']
      end;
    
      TSun = class(TInterfacedObject, IBase)
      private
        FObject: TObject;
      public
        constructor Create(AObject: TObject);
        destructor Destroy; override;
      end;
    
    implementation
    
    uses
      SysUtils;
    
    constructor TSun.Create(AObject: TObject);
    begin
      FObject := AObject;
    end;
    
    destructor TSun.Destroy;
    begin
      // 销毁时,释放传入的对象
      FreeAndNil(FObject);
      inherited;
    end;
    
    end.

    调用单元如下

    unit frmMain;
    
    // Download by http://www.codefans.net
    interface
    
    uses
      Windows,
      Messages,
      SysUtils,
      Variants,
      Classes,
      Graphics,
      Controls,
      Forms,
      Dialogs,
      StdCtrls;
    
    type
      TDeath = class(TObject)
      public
        destructor Destroy; override;
      end;
    
      TForm1 = class(TForm)
        Button1: TButton;
        Button2: TButton;
        procedure Button1Click(Sender: TObject);
        procedure Button2Click(Sender: TObject);
      private
        procedure WaitAWhile;
      public
        {Public declarations}
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    uses
      mtReaper;
    {$R *.dfm}
    
    
    destructor TDeath.Destroy;
    begin
      showMessage('对象销毁了!');
      inherited;
    end;
    
    procedure TForm1.WaitAWhile;
    var
      i: Integer;
    begin
      for i := 0 to 5000 do
      begin
        Caption := Inttostr(i);
      end;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      m_Death: TDeath;
    begin
      m_Death := TDeath.Create;
      try
        WaitAWhile;
      finally
        m_Death.Free;
      end;
    end;
    
    procedure TForm1.Button2Click(Sender: TObject);
    var
      m_Death: TDeath;
      m_Base:  IBase;
    begin
      m_Death := TDeath.Create;
      // interface接口,不用手动释放,调用完之后,生命就结束了
      m_Base := TSun.Create(m_Death);
      WaitAWhile;
    end;
    
    end.
  • 相关阅读:
    生成微博授权URL及回调地址
    微博三方登录
    celery异步发送短信
    celery配置
    celery原理与组件
    Django----短信验证接口
    Django----图片验证码接口
    编写注册接口
    jwt安装配置
    day19-Exception
  • 原文地址:https://www.cnblogs.com/tianpan2019/p/11482475.html
Copyright © 2011-2022 走看看