TValueCast (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Code

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Rtti, SysUtils;

type
  TDescendant = class(TObject)
  public
    procedure P;
  end;

procedure TDescendant.P;
begin
  if Self is TDescendant then
    Writeln('I got here OK');
end;

procedure Use(AValue: TValue);
begin
  Writeln(AValue.ToString);
end;

procedure Go;
var
  val: TValue;
  valInt: Integer;
  valByte: Byte;

begin
  { Defaults to empty }
  Writeln(val.ToString);

  { Empty is convertible to reference types }
  Writeln(val.IsObject, ' (expected TRUE)');
  Writeln(val.AsObject = nil, ' (expected TRUE)');

  { Static casting using generics }
  val := TObject(TDescendant.Create);
  val.AsType<TDescendant>.P;

  { Static casting using non-object types }
  valInt := 42;
  val := valInt;               { val will be 42 }
  valByte := val.AsType<Byte>; { but as a byte is OK too }
  Writeln('Expect 42: ', valByte);

  { Dynamic casting using type-info pointers }
  valInt := 101;
  TValue.Make(@valInt, TypeInfo(Integer), val);
  val.Cast(TypeInfo(Byte)).ExtractRawData(@valByte);
  Writeln('Verify still 101: ', valByte);
end;

begin
  try
    Go;
  except
    on E : Exception do
      Writeln('Error: ', e.Message);
  end;

  Readln;
end.

Uses