mainform.pas

来自「《Delphi COM深入编程》原书光盘」· PAS 代码 · 共 116 行

PAS
116
字号
unit MainForm;

interface

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

type
  TForm1 = class(TForm)
    btnAsObject: TButton;
    Memo1: TMemo;
    btnAsInterface: TButton;
    btnExplicitDestroy: TButton;
    btnFunction: TButton;
    btnConstFunction: TButton;
    procedure btnAsObjectClick(Sender: TObject);
    procedure btnAsInterfaceClick(Sender: TObject);
    procedure btnExplicitDestroyClick(Sender: TObject);
    procedure btnFunctionClick(Sender: TObject);
    procedure btnConstFunctionClick(Sender: TObject);
  private
    { Private declarations }
    procedure ShowName(Intf: IFormattedNumber);
    procedure ShowNameConst(const Intf: IFormattedNumber);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.btnAsObjectClick(Sender: TObject);
var
  MyInt: TFormattedInteger;
begin
  MyInt := TFormattedInteger.Create(12);
  Memo1.Lines.Add(MyInt.FormattedString);
  MyInt.Free;  // You must free MyInt

  Memo1.Lines.Add('End of Procedure');
  Memo1.Lines.Add('');
end;

procedure TForm1.btnAsInterfaceClick(Sender: TObject);
var
  MyIntf: IFormattedNumber;
begin
  MyIntf := TFormattedHexInteger.Create(1537);
  Memo1.Lines.Add(MyIntf.FormattedString);

  Memo1.Lines.Add('End of Procedure');
  Memo1.Lines.Add('');

  // MyIntf is automatically destroyed here
end;

procedure TForm1.btnExplicitDestroyClick(Sender: TObject);
var
  MyIntf: IFormattedNumber;
begin
  MyIntf := TFormattedInteger.Create(3);
  Memo1.Lines.Add(MyIntf.FormattedString);
  MyIntf := nil;    // Explicitly destroy object

  Memo1.Lines.Add('End of Procedure');
  Memo1.Lines.Add('');
end;

procedure TForm1.ShowName(Intf: IFormattedNumber);
begin
  Memo1.Lines.Add(Intf.GetName);
end;

procedure TForm1.btnFunctionClick(Sender: TObject);
var
  MyInt: TFormattedInteger;
  MyHexIntf: IFormattedNumber;
begin
  MyInt := TFormattedInteger.Create(27);
  ShowName(MyInt);
  // MyInteger is automatically destroyed here

  // MyInt.Free;  This will cause an access violation!

  MyHexIntf := TFormattedHexInteger.Create(2047);
  ShowName(MyHexIntf);

  Memo1.Lines.Add('End of Procedure');
  Memo1.Lines.Add('');
end;

procedure TForm1.ShowNameConst(const Intf: IFormattedNumber);
begin
  Memo1.Lines.Add(Intf.GetName);
end;

procedure TForm1.btnConstFunctionClick(Sender: TObject);
var
  MyInt: TFormattedInteger;
begin
  MyInt := TFormattedInteger.Create(27);
  ShowNameConst(MyInt);
  MyInt.Free;

  Memo1.Lines.Add('End of Procedure');
  Memo1.Lines.Add('');
end;

end.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?