使用RTTI读写枚举属性 as Integer

Use RTTI to read and write enumerated property as Integer

我知道如何将枚举 属性 作为字符串写入:


    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

但是如果我没有字符串而是整数(例如 fsStayOnTop 为 3),如何设置值,以及如何从 属性 中读取但不返回字符串(可以与 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

从这样的序数创建 TValue

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

在另一个方向,要读取序数,请执行以下操作:

OrdinalValue := Value.AsOrdinal;

尝试这样的事情:

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;