在对象pascal中声明一个接口并将其用作返回值

nag*_*lzs 2 delphi delphi-7

使用Delphi 7.这是一个(不完整的)示例,演示了我的问题:

interface
uses Classes, Contnrs;

type
   IEditorModule = interface;
   procedure Method1;
   procedure Method2;
   end;

   TEditorModuleList = class(TList)
   protected
    function GetItem(Index: Integer): IEditorModule;
    procedure SetItem(Index: Integer; const Value: IEditorModule);
   public
    property  Items[Index: Integer]: IEditorModule
      read GetItem write SetItem; default;   
   end;

implementation

function TEditorModuleList.GetItem(Index: Integer): IEditorModule;
begin
  Result := IEditorModule(inherited Items[index]);
end;
Run Code Online (Sandbox Code Playgroud)

无法编译,因为我收到此错误:

[错误] LEditorModule.pas(73):不兼容的类型:'IEditorModule'和'TObject'

声明新TList后代的主要原因是能够执行以下操作:

aModuleList[3].Method1;
Run Code Online (Sandbox Code Playgroud)

什么样的语法允许我将对象强制转换为接口(而不是具体的类)?事实:

  • 我不能让TEditorModule成为一个类.它需要是一个接口,因为完全不同的层次结构中的类将实现它.
  • 我需要一个类来存储实现IEditorModule接口的对象列表的引用.

我该怎么做呢?

Gra*_*ter 6

最简单的方法是使用TInterfaceList作为接口.它在Delphi 7中可用.TInterfaceList中内置了一些逻辑来管理引用计数,例如在清除列表时将它们设置为nil.

如果查看TInterfaceList背后的代码,您将看到发生的一些操作.

你要注意的一件事是TInterfaceList在内部使用TThreadList,因此在锁定和解锁列表时会有一些开销.