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...
type
Type2Type
type
OriginalType = T;
end;
TFoo
class procedure WriteLn(Dummy:Type2Type
class procedure WriteLn(Dummy:Type2Type
class procedure WriteLn(Dummy:Type2Type
private
class procedure Bar;
end;
{ TFoo
class procedure TFoo
begin
WriteLn(Type2Type
end;
class procedure TFoo
begin
ShowMessage('int');
end;
class procedure TFoo
begin
ShowMessage('string');
end;
class procedure TFoo
begin
ShowMessage('Unknown');
end;
Example :
procedure TForm1.Button1Click(Sender: TObject);
begin
TFoo
// TFoo
end;
What do you think ?
Now I search to identify if T inherit from TObject...
Lars Fosdal In general when you use generics first rule to follow would be that you have to forget about what T actually is.
ReplyDeleteBut like with any other rule, there are worthy exceptions :)
Lars Fosdal I just recently wrote why that statement is not true: http://delphisorcery.blogspot.de/2014/10/the-real-power-of-generics.html
ReplyDeleteAlso 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#).
Well, I am not a purist, but a pragmatical programmer. If it solves my problem, it is good enough.
ReplyDelete