【问题标题】:Use RTTI to read and write enumerated property as Integer使用 RTTI 将枚举属性读取和写入为 Integer
【发布时间】:2015-12-12 02:21:48
【问题描述】:

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

变量 形式:TForm; LContext:TRttiContext; LType:TRttiType; LProperty:TRttiProperty; PropTypeInfo:PTypeInfo; 值:TValue; 开始 表格 := TForm.Create(NIL); LContext := TRttiContext.Create; LType := LContext.GetType(Form.ClassType); 对于 LType.GetProperties 中的 LProperty 做 如果 LProperty.Name = 'FormStyle' 那么 开始 PropTypeInfo := LProperty.PropertyType.Handle; TValue.Make(GetEnumValue(PropTypeInfo, 'fsStayOnTop'), PropTypeInfo, Value); LProperty.SetValue(Form, Value); 结尾; writeln(整数(Form.FormStyle)); // = 3

但是如果我没有字符串而是整数(例如,fsStayOnTop 为 3),如何设置值,以及如何从该属性读取但不返回字符串(这将与 Value.AsString 一起使用)?

值 := LProperty.GetValue(Obj); writeln(Value.AsString); // 返回 fsStayOnTop 但我不想要一个字符串,我想要一个整数 writeln(Value.AsInteger); // 失败

【问题讨论】:

    标签: delphi delphi-xe8 delphi-10-seattle


    【解决方案1】:

    试试这样的:

    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;
    

    【讨论】:

    • 为什么要转换成整数而不是使用 ord()?
    • 我尝试了类似的方法,但失败了。也很好用,谢谢
    【解决方案2】:

    从这样的序数创建TValue

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

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

    OrdinalValue := Value.AsOrdinal;
    

    【讨论】:

      猜你喜欢
      • 2019-06-30
      • 2020-08-05
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多