如何在Delphi中将接口转换为对象 [英] How to cast a Interface to a Object in Delphi

查看:875
本文介绍了如何在Delphi中将接口转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在delphi 2009中,我引用了一个 IInterface ,我想将其转换为底层的 TObject p>

使用 TObject(IInterface)显然不能在Delphi 2009中工作(它应该在Delphi 2010中工作) / p>

我的搜索引导我到一个函数,应该做的技巧,但它不工作,我得到AV,当我尝试调用方法对返回的对象。



我不能真正修改类,我知道这会打断OOP

解决方案

p>而不是依赖于Delphi的内部对象布局,你也可以让你的对象实现另一个接口,只是返回对象。这当然是有效的,如果你有权访问对象的源代码开始,但你可能不应该甚至使用这些黑客,如果你没有访问对象的源代码。

  interface 

type
IGetObject = interface
function GetObject:TObject;
end;

TSomeClass = class(TInterfacedObject,IGetObject)
public
function GetObject:TObject;
end;

实现

函数TSomeClass.GetObject:TObject;
begin
结果:= Self;
end;


In delphi 2009 I have a reference to a IInterface which I want to cast to the underlying TObject

Using TObject(IInterface) obviously doesn't work in Delphi 2009 (it's supposed to work in Delphi 2010 though)

My searches lead me to a function that should do the trick, but it doesn't work for me, I get AV's when I try to call methods on the returned object.

I can't really modify the Classes and I know that this breaks OOP

解决方案

Instead of relying on Delphi's internal object layout you could also have your objects implement another interface which would simply return the object. This, of course, only works if you have access to the source code of the objects to begin with, but you probably shouldn't even use these hacks if you don't have access the source code of the objects.

interface 

type
  IGetObject = interface
    function GetObject: TObject;
  end;

  TSomeClass = class(TInterfacedObject, IGetObject)
  public
    function GetObject: TObject;
  end;

implementation

function TSomeClass.GetObject: TObject;
begin
  Result := Self;
end;

这篇关于如何在Delphi中将接口转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆