Ric*_*ler 4 delphi generics spring4d
我正在尝试实现 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.
Run Code Online (Sandbox Code Playgroud)
我知道我可以在上面的示例中将 IMyObjChild 更改为 TMyObjChild,但如果我在另一个单元或表单中需要它,那么我该怎么做?
当您需要 TObjectList 时,尝试仅对接口进行编程似乎太困难或不可能。
Grrr...有什么想法或帮助吗?
CreateObjectList有一个通用约束,其类型参数是一个类:
function CreateObjectList<T: class>(...): IList<T>;\nRun Code Online (Sandbox Code Playgroud)\n\n您的类型参数不满足该约束,因为它是一个接口。对象列表的特点是它保存对象。如果你看一下TObjectListin,Spring.Collections.Lists你会发现它也有一个通用约束,即它的类型参数是一个类。由于CreateObjectList要创建一个TObjectList<T>,因此它必须反映类型约束。
的存在理由TObjectList<T>是通过OwnsObjects. 与同名的经典 Delphi RTL 类的做法非常相似。当然,您持有接口,因此您根本不需要此功能。你应该打电话CreateList来代替。一个 plainTList<T>就是你所需要的,即使你通过IList<T>界面引用它。
LMyList := TCollections.CreateList<IMyObjChild>;\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
6081 次 |
| 最近记录: |