How to know what type is a var?

后端 未结 3 658
温柔的废话
温柔的废话 2020-12-09 20:15

TypeInfo(Type) returns the info about the specified type, is there any way to know the typeinfo of a var?

var
  S: string;
  Instance: IObjectType;
  Obj: TD         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-09 21:13

    With generics, it is now possible to get the type info without specifying it. Certain users indicated the following code doesn't compile without errors. As of Delphi 10 Seattle, version 23.0.20618.2753, it compiles without errors, as seen below in the screenshot.

    program TypeInfos;
    {$APPTYPE CONSOLE}
    {$R *.res}
    
    uses
      System.SysUtils, System.TypInfo;
    
    type
      TTypeInfo = class
        class procedure ShowTypeInfo(const X: T);
      end;
    
    { TTypeInfo }
    
    class procedure TTypeInfo.ShowTypeInfo(const X: T);
    var
      LTypeInfo: PTypeInfo;
    begin
      LTypeInfo := TypeInfo(T);
      WriteLn(LTypeInfo.Name);
    end;
    
    var
      L: Exception;
      B: Boolean;
    begin
                                 // Console output
      TTypeInfo.ShowTypeInfo(L); // Exception
      TTypeInfo.ShowTypeInfo(B); // Boolean
    end.
    

提交回复
热议问题