Ale*_*nov 7 delphi generics type-inference delphi-xe
我正在尝试编写一个接受匹配参数类型的泛型函数.
Delphi确实在普通参数的简单情况下正确地推断出类型参数.
例如:
type
TFoo = class
function Pair<T>(e1, e2: T): TList<T>;
end;
Run Code Online (Sandbox Code Playgroud)
调用它aFoo.Pair(1, 2);
可以很好地工作,但是当我将参数签名更改为泛型类型时
type
TFoo = class
function InsertInto<T>(aList: TList<T>; aVal: T): TList<T>;
end;
Run Code Online (Sandbox Code Playgroud)
并试着打电话给它
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
但它实际上是一种不同的类型.
就像在这个例子中的位置Int1
和Int2
类型不同:
var
Int1: array[1..10] of Integer;
Int2: array[1..10] of Integer;
...
Int1 := Int2; // <== BOOM! E2008 Incompatible types (in XE2)
Run Code Online (Sandbox Code Playgroud)
实际问题不在于类型推断,而是根据Pascal/Delphi的严格规则,类型不兼容.
归档时间: |
|
查看次数: |
1158 次 |
最近记录: |