I find this trick to identify 'T' Type in a delphi generic and select the appropriate code. I create a "dummy" parameter to identify the type of T...

I find this trick to identify 'T' Type in a delphi generic and select the appropriate code. I create a "dummy" parameter to identify the type of T... 

type
  Type2Type = class
  type
    OriginalType = T;
  end;

  TFoo = class
    class procedure WriteLn(Dummy:Type2Type);overload;static;inline;
    class procedure WriteLn(Dummy:Type2Type);overload;static;inline;
    class procedure WriteLn(Dummy:Type2Type);overload;static;inline;
  private
    class procedure Bar;
  end;

{ TFoo }

class procedure TFoo.Bar;
begin
  WriteLn(Type2Type(nil));
end;

class procedure TFoo.WriteLn(Dummy: Type2Type);
begin
  ShowMessage('int');
end;

class procedure TFoo.WriteLn(Dummy: Type2Type);
begin
  ShowMessage('string');
end;

class procedure TFoo.WriteLn(Dummy: Type2Type);
begin
  ShowMessage('Unknown');
end;

Example :

procedure TForm1.Button1Click(Sender: TObject);
begin
  TFoo.Bar;      //ShowMessage('int'); 
//  TFoo.Bar;
end;

What do you think ?
Now I search to identify if T inherit from TObject...

Comments

  1. Lars Fosdal In general when you use generics first rule to follow would be that you have to forget about what T actually is.

    But like with any other rule, there are worthy exceptions :)

    ReplyDelete
  2. Lars Fosdal I just recently wrote why that statement is not true: http://delphisorcery.blogspot.de/2014/10/the-real-power-of-generics.html

    Also when dealing with more dynamic code you might want to know what type T is. It would be even useful to be able to create generic types at runtime (like you can do in C#).

    ReplyDelete
  3. Well, I am not a purist, but a pragmatical programmer. If it solves my problem, it is good enough.

    ReplyDelete

Post a Comment