我想用某种方式在delphi中编写一个函数,如下面的
procedure Foo<T>;
begin
if T = String then
begin
//Do something
end;
if T = Double then
begin
//Do something else
end;
end;
ie:我希望能够根据泛型类型
执行不同的操作我尝试在TypeInfo
中使用System
,但这似乎适合于对象而不是泛型类型。
我甚至不确定在pascal中是否可行
答案 0 :(得分:11)
从XE7开始,您可以使用GetTypeKind
查找type kind:
case GetTypeKind(T) of
tkUString:
....
tkFloat:
....
....
end;
当然tkFloat
标识所有浮点类型,因此您也可以测试SizeOf(T) = SizeOf(double)
。
旧版本的Delphi没有GetTypeKind
内在版本,您必须使用PTypeInfo(TypeInfo(T)).Kind
。 GetTypeKind
的优点是编译器能够对其进行评估并优化掉可以证明不被选中的分支。
所有这些都相当违背了仿制药的目的,人们想知道你的问题是否有更好的解决方案。
答案 1 :(得分:7)
TypeInfo
应该有效:
type
TTest = class
class procedure Foo<T>;
end;
class procedure TTest.Foo<T>;
begin
if TypeInfo(T) = TypeInfo(string) then
Writeln('string')
else if TypeInfo(T) = TypeInfo(Double) then
Writeln('Double')
else
Writeln(PTypeInfo(TypeInfo(T))^.Name);
end;
procedure Main;
begin
TTest.Foo<string>;
TTest.Foo<Double>;
TTest.Foo<Single>;
end;