interface的内存自动释放的例子1

unit Unit1;

interface

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

type

  IMyinterface = interface
    function GetResult: Double;
  end;

  TMyClass = class(TInterfacedObject, IMyinterface)
    function GetResult: Double;
  end;

  TForm1 = class(TForm)
    btnInterface: TButton;
    btnClass: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btnInterfaceClick(Sender: TObject);
    procedure btnClassClick(Sender: TObject);
  private
    { Private declarations }
    FMyinterface: IMyinterface;
    FMyClass: TMyClass;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btnClassClick(Sender: TObject);
begin
  FMyClass := TMyClass.Create;
  FMyClass := TMyClass.Create;
  FMyClass := TMyClass.Create;                       //关闭窗口的时候会报内存泄露
end;

procedure TForm1.btnInterfaceClick(Sender: TObject);
begin
  FMyinterface := TMyClass.Create;
  FMyinterface := TMyClass.Create;
  FMyinterface := TMyClass.Create;                    //关闭窗口的时候不会报内存泄露
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ReportMemoryLeaksOnShutdown := True;
end;

{ TMyClass }

function TMyClass.GetResult: Double;
begin
  Result := 10;
end;

end.

 

你可能感兴趣的:(Delphi,delphi,接口)