【发布时间】: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,我会接受您的解决方案,请将其发布为答案。
-
接口指针和对象指针不可互换的原因是接口是引用计数的(即托管类型)而类不是。