Delphi: determine the actual generic type?

Is there a way to determine the type of variable passed as an argument to a method? Consider the class:

TSomeClass = class procedure AddToList<T: TDataType; U: TListClass<T>>(Element: T; List: U); end; 

with method implementation

 procedure TSomeClass.AddToList<T, U>(Element: T; List: U); begin if Element is TInt then List.AddElement(TInt.Create(XXX)) else if Element is TString then List.AddElement(TString.Create(YYY)); end; 

where TInt.Create () and TString.Create () have different sets of arguments, but they both inherit from TDataType.

Now I know that the is operator cannot be used like that, but is there a legitimate alternative that does what I ask here?

+5
generics delphi
source share
2 answers

Inability to use the operator here is a known issue, but there is a pretty simple workaround.

  if TObject(Element) is TInt then List.AddElement(TInt.Create(XXX)) 

Also, since the generic type is part of the class and known at compile time, you might be better off rebuilding your code. Make two different general classes, one of which takes a TInt as its <T> parameter, and the other takes a TString. Put the type functionality in them at this level and ask them to go down from a common ancestor to work together.

+5
source share

This question I asked a while ago

Conditional type-based behavior for a generic class

may be of interest, especially if you want to use not only TObject descendants, but also primitive types in your conditional expressions.

+4
source share

All Articles