• TObject、Pointer、Interface的转换


    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.
  • 相关阅读:
    【转】折腾好windows 7和windows 2003双系统
    【转】ndis 相关资料
    【转】自己开发程序管理WINDOWS防火墙
    你给信息工程专业本科大一的学生推荐些什么书?
    【转】如何禁止指定IP访问我的计算机
    【转】一个C#写的调用外部进程类
    【转】Crossbow携手微软,全新工具包推进无线传感器应用开发
    【转】RFC整理分类
    【转】国内外物联网技术研究进展
    【链】SmartBits600测试指导书
  • 原文地址:https://www.cnblogs.com/igaoshang/p/ObjectToInterface.html
Copyright © 2020-2023  润新知