在delphi中测试泛型的类型

sav*_*sav 9 delphi generics pascal delphi-xe6

我想用一些方法在delphi中编写一个函数,如下所示

procedure Foo<T>;
begin
    if T = String then
    begin
        //Do something
    end;

    if T = Double then
    begin
        //Do something else
    end;
end;
Run Code Online (Sandbox Code Playgroud)

即:我希望能够根据泛型类型做不同的事情

我尝试过使用TypeInfo,System但这似乎适合于对象而不是泛型类型.

我甚至不确定帕斯卡是否可行

Dav*_*nan 11

从XE7开始,您可以使用GetTypeKind以查找类型:

case GetTypeKind(T) of
tkUString:
  ....
tkFloat:
  ....
....
end;
Run Code Online (Sandbox Code Playgroud)

当然,tkFloat标识所有浮点类型,以便您也可以测试SizeOf(T) = SizeOf(double).

较旧版本的Delphi没有GetTypeKind内在版本,您必须使用它PTypeInfo(TypeInfo(T)).Kind.优点GetTypeKind是编译器能够对其进行评估并优化掉可以证明不被选中的分支.

所有这些都违背了泛型的目的,人们想知道你的问题是否有更好的解决方案.

  • FWIW我链接到GetTypeKind doc,尽管它没有记录,希望有一天Emba文档会赶上. (2认同)

Ond*_*lle 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;
Run Code Online (Sandbox Code Playgroud)