Search code examples
delphidelphi-xe8delphi-10-seattle

Use RTTI to read and write enumerated property as Integer


I do know how to write to an enum property as a string:


    var
      Form: TForm;
      LContext: TRttiContext;
      LType: TRttiType;
      LProperty: TRttiProperty;
      PropTypeInfo: PTypeInfo;
      Value: TValue;

    begin
      Form := TForm.Create(NIL);
      LContext := TRttiContext.Create;

      LType := LContext.GetType(Form.ClassType);
      for LProperty in LType.GetProperties do
        if LProperty.Name = 'FormStyle' then
        begin
          PropTypeInfo := LProperty.PropertyType.Handle;
          TValue.Make(GetEnumValue(PropTypeInfo, 'fsStayOnTop'), PropTypeInfo, Value);
          LProperty.SetValue(Form, Value);
        end;

      writeln(Integer(Form.FormStyle));  // = 3

but how to set the value if I don't have a string but an integer (e.g. 3 for fsStayOnTop) and how to read from that property but not returning a string (which would work with Value.AsString)?


     Value := LProperty.GetValue(Obj);
     writeln(Value.AsString);  // returns fsStayOnTop but I want not a string, I want an integer
     writeln(Value.AsInteger);  // fails


Solution

  • Create the TValue from an ordinal like so:

    Value := TValue.FromOrdinal(PropTypeInfo, OrdinalValue);
    

    In the other direction, to read an ordinal do this:

    OrdinalValue := Value.AsOrdinal;