zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    Python异常处理
    Python 线程、进程和协程
    python版本升级及pip部署方法
    Python socket编程
    循环遍历方法笔记
    TCP/IP协议分为哪四层,具体作用是什么。
    Python Paramiko模块与MySQL数据库操作
    Python面向对象编程(二)
    h5专题常用小代码
    sethc问题
  • 原文地址:https://www.cnblogs.com/igaoshang/p/ObjectToInterface.html
Copyright © 2011-2022 走看看