【问题标题】:Declare an interface in object pascal and use it as return value在 object pascal 中声明一个接口并将其用作返回值
【发布时间】:2014-05-26 08:39:44
【问题描述】:

使用 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;

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

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

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

aModuleList[3].Method1;

哪种语法可以让我将对象转换为接口(而不是具体的类)?事实:

  • 我无法将 TEditorModule 设为一个类。它必须是一个接口,因为完全不同的层次结构中的类会实现它。
  • 我需要一个类来存储实现 IEditorModule 接口的对象列表的引用。

我该怎么做?

【问题讨论】:

  • 您应该对接口使用 TInterfaceList 而不是 TList。我相信它在 Delphi 7 中可用。
  • 如果您删除“;”,您的代码将为我编译在接口一词之后并实现 setitem。
  • TInterfaceList 有效!虽然我不确定为什么不能将接口转换为对象或返回。它们都表示为指针,那么原因是什么? Graymatter,我会接受您的解决方案,请将其发布为答案。
  • 接口指针和对象指针不可互换的原因是接口是引用计数的(即托管类型)而类不是。

标签: delphi-7 delphi


【解决方案1】:

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

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

您应该注意的一点是,TInterfaceList 在内部使用 TThreadList,因此在锁定和解锁列表时会产生一些开销。

【讨论】:

    猜你喜欢
    • 2012-03-27
    • 2023-03-16
    • 2011-03-30
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多