且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Delphi中将接口转换为对象

更新时间:2023-02-10 21:28:48

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;