将对象转换为接口类型,不将TInterfacedObject作为基类

Mic*_*ieł 9 delphi interface delphi-xe2

我需要一个没有引用计数的类实现接口.我做了以下事情:

  IMyInterface = interface(IInterface)
      ['{B84904DF-9E8A-46E0-98E4-498BF03C2819}'] 
      procedure InterfaceMethod;
  end;

  TMyClass = class(TObject, IMyInterface)
  protected
      function _AddRef: Integer;stdcall;
      function _Release: Integer;stdcall;
      function QueryInterface(const IID: TGUID; out Obj): HResult;stdcall;
  public
      procedure InterfaceMethod;
  end;

  procedure TMyClass.InterfaceMethod;
  begin
      ShowMessage('The Method');
  end;

  function TMyClass.QueryInterface(const IID: TGUID; out Obj): HResult;
  begin
      if GetInterface(IID, Obj) then
          Result := 0
      else
          Result := E_NOINTERFACE;
  end;

  function TMyClass._AddRef: Integer;
  begin
      Result := -1;
  end;

  function TMyClass._Release: Integer;
  begin
      Result := -1;
  end;
Run Code Online (Sandbox Code Playgroud)

缺少引用计数工作正常.但我担心的是,我不能投TMyClass给IMyInterface使用as操作:

var
  MyI: IMyInterface; 
begin
  MyI := TMyClass.Create as IMyInterface;
Run Code Online (Sandbox Code Playgroud)

我得到了

[DCC错误] E2015运算符不适用于此操作数类型

TMyClass派生时问题消失了TInterfacedObject- 即我可以在没有编译器错误的情况下进行此类转换.显然我不想使用TInterfacedObject作为基类,因为它会使我的类引用计数.为什么不允许这样的演员以及如何解决它?

Dav*_*nan 15

您无法as在代码中使用的原因是您的类未IInterface在其支持的接口列表中明确列出.即使您的接口派生自IInterface,除非您实际列出该接口,否则您的类不支持它.

所以,简单的解决方法是声明你的类是这样的:

TMyClass = class(TObject, IInterface, IMyInterface)
Run Code Online (Sandbox Code Playgroud)

您的类需要实现的原因IInterface是编译器为了实现强制转换而依赖的原因as.

我想说的另一点是,一般来说,你应该避免使用接口继承.总的来说它没什么用处.使用接口的一个好处是,您不受实现继承附带的单继承约束的影响.

但无论如何,所有Delphi接口都会自动继承,IInterface所以在你的情况下,没有必要指明这一点.我会声明你的界面:

IMyInterface = interface
  ['{B84904DF-9E8A-46E0-98E4-498BF03C2819}'] 
  procedure InterfaceMethod;
end;
Run Code Online (Sandbox Code Playgroud)

更广泛地说,您应该尽量不在接口上使用继承.采用这种方法可以减少耦合,从而提高灵活性.