GS

被sgao忘记的东西都在这里。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

TObject、Pointer、Interface的转换

Posted on 2016-08-04 13:54  sgao  阅读(839)  评论(0编辑  收藏  举报
unit Unit4;

interface

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

type
  //测试接口
  ITest = interface
    function GetName: string;
  end;

  //接口实现类
  TTest = class(TInterfacedObject, ITest)
  public
    function GetName: string;
  end;

  //测试窗体
  TForm4 = class(TForm)
    btn1: TButton;
    mmo1: TMemo;
    procedure btn1Click(Sender: TObject);
  end;

var
  Form4: TForm4;

implementation

{$R *.dfm}

{ TTest }

function TTest.GetName: string;
begin
  Result := 'igaoshang.cnblogs.com'
end;

//点击测试按钮
procedure TForm4.btn1Click(Sender: TObject);
var
  LTestObj: TTest;
  LTestInf: ITest;
  LObj1, LObj2: TObject;
  LInf1, LInf2: ITest;
begin
  //创建接口对象
  LTestObj := TTest.Create;
  mmo1.Lines.Add('LTestObj地址:' + IntToHex(Integer(Pointer(LTestObj)),0));
  //给接口赋值
  LTestInf := LTestObj;
  //将接口转为Obj
  LObj1 := TObject(LTestInf);     //将接口对象地址赋值给了LObj1,但丢失了接口信息
  mmo1.Lines.Add('LObj1地址:' + IntToHex(Integer(Pointer(LObj1)),0));   //LTestObj地址 = LObj1地址
  LObj2 := TObject(Pointer(LTestInf));  //保留了接口信息,但生成了新的指针
  mmo1.Lines.Add('LObj2地址:' + IntToHex(Integer(Pointer(LObj2)),0));
  //将Obj转为接口
  
//LInf1 := ITest(Pointer(LObj1));       //无法转换了,丢失了接口信息
  
//mmo1.Lines.Add(LInf1.GetName);
  LInf1 := ITest(TTest(LObj1));           //可以这样转换
  mmo1.Lines.Add(LInf1.GetName);
  LInf2 := ITest(Pointer(LObj2));         //可以将对象直接转换成接口
  mmo1.Lines.Add(LInf2.GetName);
end;

end.