[英]Testing the type of a generic in delphi
I want some way to write a function in delphi like the following 我想用一些方法在delphi中编写一个函数,如下所示
procedure Foo<T>;
begin
if T = String then
begin
//Do something
end;
if T = Double then
begin
//Do something else
end;
end;
ie: I want to be able to do different things based on a generic type 即:我希望能够根据泛型类型做不同的事情
I've tried using TypeInfo
in System
but this seems to be suited to objects rather than generic types. 我尝试在
System
使用TypeInfo
,但这似乎适合于对象而不是泛型类型。
I'm not even sure this is possible in pascal 我甚至不确定帕斯卡是否可行
From XE7 onwards you can use GetTypeKind
to find the type kind : 从XE7开始,您可以使用
GetTypeKind
查找类型类型 :
case GetTypeKind(T) of
tkUString:
....
tkFloat:
....
....
end;
Of course tkFloat
identifies all floating point types so you might also test SizeOf(T) = SizeOf(double)
. 当然
tkFloat
标识所有浮点类型,因此您也可以测试SizeOf(T) = SizeOf(double)
。
Older versions of Delphi do not have the GetTypeKind
intrinsic and you have to use PTypeInfo(TypeInfo(T)).Kind
instead. 较旧版本的Delphi没有
GetTypeKind
内在函数,您必须使用PTypeInfo(TypeInfo(T)).Kind
。 The advantage of GetTypeKind
is that the compiler is able to evaluate it and optimise away branches that can be proven not to be selected. GetTypeKind
的优点是编译器能够对其进行评估并优化掉可以证明不被选中的分支。
All of this rather defeats the purpose of generics though and one wonders if your problem has a better solution. 所有这些都违背了泛型的目的,人们想知道你的问题是否有更好的解决方案。
TypeInfo
should work: 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.