如何在 Delphi 中将接口转换为对象 [英] How to cast a Interface to a Object in Delphi
问题描述
在 delphi 2009 中,我有一个对 IInterface
的引用,我想将其转换为底层的 TObject
In delphi 2009 I have a reference to a IInterface
which I want to cast to the underlying TObject
使用 TObject(IInterface)
显然在 Delphi 2009 中不起作用(它应该在 Delphi 2010 中工作)
Using TObject(IInterface)
obviously doesn't work in Delphi 2009 (it's supposed to work in Delphi 2010 though)
我的搜索使我a应该可以解决问题的函数,但它对我不起作用,当我尝试在返回的对象上调用方法时,我得到了 AV.
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.
我无法真正修改类,我知道这会破坏 OOP
推荐答案
除了依赖 Delphi 的内部对象布局,您还可以让您的对象实现另一个接口,该接口将简单地返回对象.当然,这只有在您有权访问对象的源代码的情况下才有效,但如果您无法访问对象的源代码,您甚至不应该使用这些技巧.
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屋!