且构网

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

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

更新时间:2023-02-10 21:47:02

除了依赖 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;