使用RTTI将枚举属性读写为Integer

cyd*_*ydo 1 delphi delphi-xe8 delphi-10-seattle

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


    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

但如果我没有字符串但是整数(例如3表示fsStayOnTop)以及如何从该属性读取但不返回字符串(可以使用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

Dav*_*nan 6

TValue从序数创建如下:

Value := TValue.FromOrdinal(PropTypeInfo, OrdinalValue);
Run Code Online (Sandbox Code Playgroud)

在另一个方向,阅读序数做这个:

OrdinalValue := Value.AsOrdinal;
Run Code Online (Sandbox Code Playgroud)