delphi - 类标题中的关键字 `constructor` 是什么意思?

标签 delphi generics

如果我有一个像这样的类声明:

MyCollection<T: TBaseCopyable, constructor> = class

关键字构造函数有什么作用?

不是每个类都有一个构造函数吗?它在做什么?

最佳答案

这是一个 generic constraint .

Constraints can be associated with a type parameter of a generic. Constraints declare items that must be supported by any particular type passed to that parameter in a construction of the generic type.

这个特定的约束是 constructor constraint :

A type parameter may be constrained by zero or one instance of the reserved word "constructor". This means that the actual argument type must be a class that defines a default constructor (a public parameterless constructor), so that methods within the generic type may construct instances of the argument type using the argument type's default constructor, without knowing anything about the argument type itself (no minimum base type requirements).

In a constraint declaration, you can mix "constructor" in any order with interface or class type constraints.

<小时/>

在我看来,这是一个基本上无用的功能。每次我编写一个希望实例化成员的通用容器类时,我发现我需要能够将参数传递给构造函数。我完全不知道为什么这个功能会以这种残缺的形式存在。

有一种众所周知的技术允许通用容器实例化成员,此处讨论:Generics constructor with parameter constraint?

关于delphi - 类标题中的关键字 `constructor` 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18943993/

相关文章:

Delphi 开发人员的 C# 标准/风格?

Delphi CreateOleObject 事件

sql - 适用于 Delphi 2010 和 Unidac 的可视化 SQL 查询生成器

c# - 实现通用接口(interface)时奇怪的 C# 行为

ios - 无法推断通用参数 'T' - 泛型问题

android - 单击弹出控件时生成的滑动 Firemonkey Delphi

delphi - 有没有一种方法可以在不改变 BorderStyle 的情况下使 Delphi VCL 窗体变大?

c# - 如果我指定了基类,为什么我不能用泛型调用参数化构造函数

c++ - C++异常捕获迟了,这可能是什么原因?

java - 是否可以将抽象方法的返回类型设置为与类相同?