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

How do I convert an enum to string and back again using RTTI in Delphi

我无法根据名称而不是序数值获取枚举类型。我需要在 class' 属性的 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;

感谢 Rudy,他让我走上了正轨。能够获得 属性 的 PTypeInfo 给了我我需要的 link。

    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';

请注意,在 Delphi 的较新版本中,您可以这样做:

S:=TRttiEnumerationType.GetName(o.CustomColor)