gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 14:53:39 27 4
gpt4 key购买 nike

我正在尝试编写一个接受匹配参数类型的通用函数。
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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com