delphi - 基于泛型参数类型的类型推断(Delphi)

标签 delphi generics delphi-xe type-inference

我正在尝试编写一个接受匹配参数类型的通用函数。
Delphi 确实在简单参数的简单情况下正确推断出类型参数。

例如:

type
  TFoo = class
    function Pair<T>(e1, e2: T): TList<T>;
  end;

aFoo.Pair(1, 2); 调用它工作得很好,但是当我将参数签名更改为泛型类型时

type
  TFoo = class
    function InsertInto<T>(aList: TList<T>; aVal: T): TList<T>;
  end;

并尝试调用它
aFoo.InsertInto(TList<String>.Create, 'bar');

然后编译器会提示它:
E2010 Incompatible types: 'Generics.Collections.TList<uTest.TFoo.InsertInto.T>' and 'Generics.Collections.TList<System.String>'

有什么方法可以编写这个(或类似的)方法,以便客户端不必指定类型参数?
aFoo.InsertInto<String>(TList<String>.Create, 'bar');

最佳答案

我的猜测是来自 Delphi 的强类型本质。
uTest.TFoo.InsertInto.T 相当于 System.String,但它实际上是不同的类型

与此示例非常相似,其中 Int1Int2 不是同一类型:

var
  Int1: array[1..10] of Integer;
  Int2: array[1..10] of Integer;
      ...
  Int1 := Int2; // <== BOOM! E2008 Incompatible types (in XE2)

实际问题不在于类型推断,而在于类型与 Pascal/Delphi 的严格规则不兼容。

关于delphi - 基于泛型参数类型的类型推断(Delphi),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12693755/

相关文章:

delphi - 带参数创建匿名线程

RadStudio/Delphi 10 中的 Git 集成

c# - 允许派生类型转换为父类型返回 `object` ,但使用派生类型的方法

java - GWT TextBox、DateBox 等不共享相同的基本输入类

delphi - 将 TRichEdit 绘制到 Canvas 上

delphi - Delphi 中比较指针与函数值

c# - 在 C# 中遇到继承和泛型问题

delphi - 如何从 Delphi 5 ActiveX dll 创建 MDI 子窗口,并将其嵌入到 Delphi XE MDI 父窗口中?

delphi - 我如何确定抽象方法是否已实现?

delphi - 在搜索值中使用单引号找到 Delphi XE2 TADO 异常