如何在Delphi中使用RTTI将枚举转换为字符串然后再次返回

时间:2018-11-19 06:02:53

标签: delphi enums rtti

我在获取基于其名称而不是顺序值的枚举类型时遇到麻烦。我需要在类属性的RTTI循环中执行此操作。我尝试使用GetEnumName和TRTTIEnumerationType.GetName,但是我似乎无法从TRTTIProperty实例中将这些东西放在一起。

请帮助? (下面的骨架代码示例)

    uses
      RTTI, TypInfo;

    type 
      TCustomColor = (ccBlack, ccBrown, ccBlue);

      TMyClass = class
      public
        property CustomColor: TCustomColor;
      end;

    procedure Output;
    var
      rc : TRTTIContext;
      rt : TRTTIType;
      rp : TRTTIProperty;
      mc : TMyClass;
    begin
      mc.CustomColor := mcBlue;
      rt := rc.GetType(mc.ClassType);
      for rp in rt.GetProperties do
        if rp.PropertyType.TypeKind = tkEnumeration then
        begin
          // TODO: Retrieve 'ccBlue' from the property
        end;
    end;

    procedureInput;
    var
      n, s : String;
      o : TObject;
      rc : TRTTIContext;
      rt : TRTTIType;
    begin
      n := 'CustomColor';
      s := 'ccBlue';
      // NOTE: o is instantiated from a string of it's classtype
      o := (rc.FindType('MyClass') as TRTTIInstanceType).MetaClassType.Create;
      rt := rc.GetType(o.ClassType);
      rt.GetProperty(n).SetValue(o, ???);  // TODO: set o.CustomColor appropriately
    end;

1 个答案:

答案 0 :(得分:1)

感谢Rudy,他使我走上了正轨。能够获取属性的PTypeInfo给了我所需的链接。

    var
      rp: TRTTIProperty;
      o : TMyClass;
      s : String;
    begin
      o.CustomColor := ccBlue;
      [...]  // loop through and assign rp to the TMyClass.CustomColor property
      s := GetEnumName(rp.GetValue(o).TypeInfo, rp.GetValue(o).AsOrdinal));
      WriteLn(s);   // 'ccBlue';