gpt4 book ai didi

Delphi 接口(interface)和 IList(或 TObjectList)

转载 作者:行者123 更新时间:2023-12-03 15:28:54 27 4
gpt4 key购买 nike

我正在尝试实现 Spring 4 Delphi,并且仅对接口(interface)而不是类进行编程。然而,当您想使用 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 时,尝试仅对接口(interface)进行编程似乎太难或不可能。

呃...有什么想法或帮助吗?

最佳答案

CreateObjectList有一个通用约束,其类型参数是一个类:

function CreateObjectList<T: class>(...): IList<T>;

您的类型参数不满足该约束,因为它是一个接口(interface)。对象列表的特点是它保存对象。如果你看一下TObjectListSpring.Collections.Lists您将看到它还具有其类型参数是类的通用约束。自从 CreateObjectList将创建一个 TObjectList<T> ,它必须反射(reflect)类型约束。

TObjectList<T> 存在的理由是通过 OwnsObjects 承担其成员的所有权。与同名的经典 Delphi RTL 类的做法非常相似。当然,您持有接口(interface),因此您根本不需要此功能。您应该调用CreateList反而。平原TList<T>是您所需要的,即使您通过 IList<T> 引用它界面。

LMyList := TCollections.CreateList<IMyObjChild>;

关于Delphi 接口(interface)和 IList<T>(或 TObjectList<T>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22679260/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com