• 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.
  • 相关阅读:
    Codeforce821E Okabe and El Psy Kongroo
    hihocoder1497 Queen Attack
    hihocoder 1523数据重排
    codeforce 780C Andryusha and Colored Balloons
    codeforce 768B Code For 1
    hihoCoder1270 建造基地 完全背包
    UVA10054 The Necklace 欧拉回路+并查集
    Codeforces Round #480 (Div. 2) C 贪心 D 数字、思维 E 树上倍增
    ZOJ 4029 Now Loading!!! 思维
    西安电子科技大学第16届程序设计竞赛网络同步赛 E dp G 找规律
  • 原文地址:https://www.cnblogs.com/tianpan2019/p/11482475.html
Copyright © 2020-2023  润新知