Delphi 如何向不使用';还不包括TInterfacedObject?

Delphi 如何向不使用';还不包括TInterfacedObject?,delphi,interface,Delphi,Interface,以下示例显示了如何开始针对接口进行编码: 从 到 IInterface = interface ['{BFC7867C-6098-4744-9774-35E0A8FE1A1D}'] function Add(a, b: integer): integer; end; TMyObject = class (TInterfacedObject, IInterface function Add(a, b: integer): integer; end; 但是如果类有一个祖先,比如说t

以下示例显示了如何开始针对接口进行编码:

IInterface = interface
  ['{BFC7867C-6098-4744-9774-35E0A8FE1A1D}']
  function Add(a, b: integer): integer;
end;

TMyObject = class (TInterfacedObject, IInterface 
  function Add(a, b: integer): integer;
end;
但是如果类有一个祖先,比如说tmyclassDerivedDirectlyFromTobjectsSoitsGotNothingItahall,我该如何管理呢

TMyObject = class(TMyClassDerivedDirectlyFromTObjectSoItsGotNothingInItAtAll)
    function Add(a, b: integer): integer;
end;

当您有一个实现接口的类时,该类必须提供三种方法:\u AddRef\u ReleaseQueryInterface。如果查看TInterfacedObject代码,您会注意到这些方法。事实上,TInterfacedObject的存在只是为了更容易地创建新的接口实现器类


如果您无法从TInterfacedObject继承新类,则必须自己提供这些方法。例如,您可以将TInterfacedObject实现复制到您的类中,然后您的类将成为接口实现者。

首先:我将重命名接口:

IMyAddFunction = interface
  ['{BFC7867C-6098-4744-9774-35E0A8FE1A1D}']
  function Add(a, b: integer): integer;
end;
如果祖先已经实现了IInterface,这并不难:

TTable继承自已经为您实现(现有)接口的TComponent。 所以你可以这样做:

TMyObject = class(TTable, IMyAddFunction)
    function Add(a, b: integer): integer;
end;
如果没有,则您必须自己实现IInterface:

IInterface = interface
  ['{00000000-0000-0000-C000-000000000046}']
  function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
  function _AddRef: Integer; stdcall;
  function _Release: Integer; stdcall;
end;

Delphi附带了源代码,因此您可以查看TComponent实现的实现,并实现AlexSC给出的答案中引用的方法。

只是一个提示:您的问题与模仿的依赖注入没有太大关系,但与接口有关,所以我想,如果你在答案上贴上界面标签,你会更成功地得到答案。你是对的。修正。不要调用自己的接口接口,它会产生名称冲突。您如何知道它是相同的
TTable
?我的
t表
未实现
i接口
。而且,
TComponent
中的实现与
TInterfacedObject
中的实现非常不同@DavidHeffernan我想不是每个TTable都继承自TComponent,我以为他在谈论用delphi打包的TTable。我感觉到这个问题是一般性的。碰巧这个类被命名为
TTable
,但它可能是
tCyclassedired直接从对象到对象的,所以答案是:如果祖先已经实现了接口,那么就自己实现它。是的,这个问题是一般性的。如果祖先尚未实现IInterface,我在哪里可以找到有关如何创建正确接口的更多详细信息?
IInterface = interface
  ['{00000000-0000-0000-C000-000000000046}']
  function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
  function _AddRef: Integer; stdcall;
  function _Release: Integer; stdcall;
end;