Yon*_*ona 13 delphi pascal casting interface delphi-2009
在delphi 2009中,我引用了一个IInterface我想要转换为底层的东西TObject
使用TObject(IInterface)显然在Delphi 2009中不起作用(它应该在Delphi 2010中工作)
我的搜索引导我找到一个应该做的技巧,但它对我不起作用,当我尝试在返回的对象上调用方法时,我得到了AV.
我无法真正修改类,我知道这打破了OOP
Lar*_*ens 19
您可以让对象实现另一个简单地返回对象的接口,而不是依赖于Delphi的内部对象布局.当然,这只有在您可以访问对象的源代码时才有效,但如果您无法访问对象的源代码,则可能甚至不应该使用这些黑客.
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;
Run Code Online (Sandbox Code Playgroud)
Arn*_*hez 17
你是对的.从Delphi 2010开始,您可以使用as运算符,例如via aObject := aInterface as TObject或甚至aObject := TObject(aInterface).
此as运算符使用特殊的隐藏接口GUID(ObjCastGUID)来检索对象实例,调用TObject.GetInterfaceDelphi 2010之前不存在的增强版本.请参阅System.pas单元的源代码以了解它的工作原理.
我已经发布了一些适用于Delphi 6到XE2的代码,包括Delphi 2009.
见http://blog.synopse.info/post/2012/06/13/Retrieve-the-object-instance-from-an-interface