Identify the type of variable received in a generic function

1

I have a function in Delphi that receives a generic data type, I would like to know what type of data is received, like this:

function MinhaFuncao<T>(): T

I need to know which type is in <T> .

    
asked by anonymous 20.10.2017 / 15:59

1 answer

0

To know the type of variable that we have in the function we can use the following procedure, for example:

procedure TForm1.ShowBasicVariantType(varVar: Variant);
var typeString: string;
   basicType : Integer;
begin
  basicType := VarType(varVar) and VarTypeMask;

  case basicType of
    varEmpty     : typeString := 'varEmpty';
    varNull      : typeString := 'varNull';
    varSmallInt  : typeString := 'varSmallInt';
    varInteger   : typeString := 'varInteger';
    varSingle    : typeString := 'varSingle';
    varDouble    : typeString := 'varDouble';
    varCurrency  : typeString := 'varCurrency';
    varDate      : typeString := 'varDate';
    varOleStr    : typeString := 'varOleStr';
    varDispatch  : typeString := 'varDispatch';
    varError     : typeString := 'varError';
    varBoolean   : typeString := 'varBoolean';
    varVariant   : typeString := 'varVariant';
    varUnknown   : typeString := 'varUnknown';
    varByte      : typeString := 'varByte';
    varWord      : typeString := 'varWord';
    varLongWord  : typeString := 'varLongWord';
    varInt64     : typeString := 'varInt64';
    varStrArg    : typeString := 'varStrArg';
    varString    : typeString := 'varString';
    varAny       : typeString := 'varAny';
    varTypeMask  : typeString := 'varTypeMask';
  end;

  ShowMessage('Variant type is '+typeString);
end;

Code to call the function:

var myVar : Variant;
begin
  ShowMessage('Variant value = not yet set');
  ShowBasicVariantType(myVar);

  myVar := 123;
  ShowMessage('Variant value = 123');
  ShowBasicVariantType(myVar);

  myVar := myVar + 456;
  ShowMessage('Variant value = 123 + 456');
  ShowBasicVariantType(myVar);

  myVar := 'String '+IntToStr(myVar);
  ShowMessage('Variant value = String 579');
  ShowBasicVariantType(myVar);
end;

Result:

  

Variant value = not yet set   Variant type = varEmpty
  Variant value = 123
  Variant type = varByte
  Variant value = 123 + 456
  Variant type = varInt64
  Variant value = String 579
  Variant type = varString

For more information, see the DelphiBasics , you can still see here has one more example possible.

    
20.10.2017 / 16:17