【发布时间】:2014-03-27 05:47:33
【问题描述】:
我正在尝试实现 Spring 4 Delphi,并且只对接口而不是类进行编程。但是,当您想使用 TObjectList 时,这似乎是不可能的。
考虑以下代码:
unit Unit1;
interface
uses
Spring.Collections,
Spring.Collections.Lists;
type
IMyObjParent = interface
['{E063AD44-B7F1-443C-B9FE-AEB7395B39DE}']
procedure ParentDoSomething;
end;
IMyObjChild = interface(IMyObjParent)
['{E063AD44-B7F1-443C-B9FE-AEB7395B39DE}']
procedure ChildDoSomething;
end;
implementation
type
TMyObjChild = class(TInterfacedObject, IMyObjChild)
protected
procedure ParentDoSomething;
public
procedure ChildDoSomething;
end;
{ TMyObj }
procedure TMyObjChild.ChildDoSomething;
begin
end;
procedure TMyObjChild.ParentDoSomething;
begin
end;
procedure TestIt;
var
LMyList: IList<IMyObjChild>;
begin
TCollections.CreateObjectList<IMyObjChild>;
//[DCC Error] Unit1.pas(53): E2511 Type parameter 'T' must be a class type
end;
end.
我知道我可以在上面的示例中将 IMyObjChild 更改为 TMyObjChild,但如果我需要在另一个单元或表单中进行更改,我该怎么做?
一旦您需要 TObjectList,就尝试只对接口进行编程似乎太难或不可能。
Grrr...有什么想法或帮助吗?
【问题讨论】:
-
你可以使用TInterfaceList。
-
如果您使用接口,则不需要 TObjectList,因为它对 TList 所做的只是管理它所持有的对象的生命周期。
-
谢谢!这几天我一直在努力解决这个问题,但由于接口是引用计数,因此可以使用 TList 代替 TObjectList。
-
FWIW,看起来您的界面具有完全相同的 GUID。这可能会成为一个问题。每个接口都应该有一个不同的接口。在编辑器中使用 Shift+Ctrl+G 生成一个新的。