泛型:什么是“CONSTRUCTOR约束”? [英] Generics: What's a "CONSTRUCTOR constraint"?
问题描述
我制作了一个自定义的TObjectList子类,用于保存基础对象类的子类。它看起来像这样:
I made a custom TObjectList descendant designed to hold subclasses of a base object class. It looks something like this:
interface
TMyDataList<T: TBaseDatafile> = class(TObjectList<TBaseDatafile>)
public
constructor Create;
procedure upload(db: TDataSet);
end;
implementation
constructor TMyDataList<T>.Create;
begin
inherited Create(true);
self.Add(T.Create);
end;
我想让每个新列表从一个空白对象开始。这很简单,对吧?但编译器不喜欢它。它说:
I want each new list to start out with one blank object in it. It's pretty simple, right? But the compiler doesn't like it. It says:
在类型参数声明中无法创建没有CONSTRUCTOR约束的新实例
我只能假设这是泛型相关的。任何人都知道发生了什么,以及我如何使这个构造函数工作。
"Can't create new instance without CONSTRUCTOR constraint in type parameter declaration" I can only assume this is something generics-related. Anyone have any idea what's going on and how I can make this constructor work?
推荐答案
您正在尝试创建一个实例 T
通过 T.Create
。这不工作,因为编译器不知道你的泛型类型有一个无参数的构造函数(记住:这不是必需的)。要纠正这个问题,你必须创建一个构造函数约束,如下所示:
You're trying to create an instance of T
via T.Create
. This doesn't work because the compiler doesn't know that your generic type has a parameterless constructor (remember: this is no requirement). To rectify this, you've got to create a constructor constraint, which looks like this:
<T: constructor>
或在您的特定情况下:
<T: TBaseDatafile, constructor>
这篇关于泛型:什么是“CONSTRUCTOR约束”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!