【问题标题】:How to define class with self-referencing generics constraint in Delphi?如何在 Delphi 中定义具有自引用泛型约束的类?
【发布时间】:2014-04-23 13:24:26
【问题描述】:

article所示,可以在C#中定义:

public class MyTreeNode<T> where T: MyTreeNode<T>
{

}

然而,在 Delphi 中,以下代码无法编译并报错“E2003 Undeclared identifier: 'MyTreeNode'”:

type
    TMyTreeNode<T: TMyTreeNode<T>> = class
    end;

正式的术语似乎是"self-referencing generics constraint"。我想知道如何在 Delphi 中做到这一点?

PS:

Another useful article as David pointed out

Relevent SO post regarding Delphi and covariance / contravariance

Wikipedia page of co/contra-variance.

【问题讨论】:

  • 你不能用 Delphi 通用约束来做到这一点
  • @DavidHeffernan 感谢您的评论!

标签: delphi generics


【解决方案1】:

在 Delphi 中没有办法表达这样一个通用的约束。此外,我相信没有类型安全的方法可以实现在 C# 中可以通过这样的约束实现的目标。

【讨论】:

  • 感谢您的评论!您能否帮助解释更多关于“没有类型安全的方法来实现在 C# 中可以通过这样的约束实现的目标”?
  • 您使用泛型是因为您想要类型安全。你可以通过放弃泛型来实现没有类型安全的容器。
  • 感谢您的评论!您能否帮助展示一个有关“您可以通过放弃泛型来实现没有类型安全的容器”的示例。 ?
  • 我想您只需删除约束,而是在将元素添加到容器时添加运行时类型检查。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多