Ste*_*nas 3 delphi generics delphi-2009
我正在尝试编写一个包含通用TObjectList <T>的泛型类,它应该只包含TItem的元素.
uses
Generics.Collections;
type
TItem = class
end;
TGenericClass<T: TItem> = class
public
SimpleList: TList<T>; // This compiles
ObjectList: TObjectList<T>; // This doesn't compile: Compiler complaints that "T is not a class type"
end;
Run Code Online (Sandbox Code Playgroud)
这是一个错误的语法吗?BTW:TGenericClass <T:class>编译,但是List中的Items不再是TItem,这是我不想要的.
通用类型可以有几个约束:
如果您创建使用其他泛型的泛型,则需要复制约束,否则它将无效.在您的情况下,TObjectList具有类约束.这意味着,你的T也需要这个约束.
不幸的是,这不能与命名的类约束结合使用.
所以我建议你使用一个接口,这些可以组合使用:
type
IItem = interface end;
TItem = class (TInterfacedObject, IItem) end;
TGenericClass<T: class, IItem> = class
private
FSimpleList: TList<T>;
FObjectList: TObjectList<T>;
end;
Run Code Online (Sandbox Code Playgroud)
此外,您应该将您的字段设为私有,其他人都可以更改它们.