1
votes

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

2

2 Answers

6
votes

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;
3
votes

Try something like this:

var
  Form: TForm;
  LContext: TRttiContext;
  LType: TRttiType;
  LProperty: TRttiProperty;
  Value: TValue;
begin
  Form := TForm.Create(NIL);

  LContext := TRttiContext.Create;
  LType := LContext.GetType(Form.ClassType);
  LProperty := LType.GetProperty('FormStyle');

  Value := TValue.From<TFormStyle>({fsStayOnTop}TFormStyle(3));
  LProperty.SetValue(Form, Value);

  WriteLn(Integer(Form.FormStyle));

  Value := LProperty.GetValue(Form);
  WriteLn(Integer(Value.AsType<TFormStyle>()));

  ...
end;