delphienumsrtti

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


I'm having trouble getting an enumerated type based on it's name, rather than ordinal value. I need to do this within an RTTI loop of a class' properties. I've tried using GetEnumName and TRTTIEnumerationType.GetName, but I can't seem to fit these things together from a TRTTIProperty instance.

Help please? (skeleton code example below)

    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 := ccBlue;
      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;
    
    procedure Input;
    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;


Solution

  • Thanks to Rudy, who put me on the right track. Being able to get the PTypeInfo of the property gave me the link I needed.

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