如何在Delphi中使用RTTI将枚举转换为字符串

t40tm48m  于 2022-09-21  发布在  其他
关注(0)|答案(2)|浏览(348)

获取基于名称而不是序数值的枚举类型时遇到了问题。我需要在类的属性的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 := 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;
rkttyhzu

rkttyhzu1#

请注意,在较新版本的Delphi中,您可以执行以下操作:

S:=TRttiEnumerationType.GetName(o.CustomColor)
93ze6v8z

93ze6v8z2#

多亏了鲁迪,他让我走上了正确的道路。能够获得属性的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';

相关问题