Generic functions for converting an enumeration to string and back

后端 未结 5 1748
终归单人心
终归单人心 2020-12-11 01:33

I\'m trying to write functions that will convert an enumeration to string and back again.

ie:

TConversions = class
    strict private
    public
            


        
5条回答
  •  天命终不由人
    2020-12-11 01:49

    There seems to be no T:enum generic type constraint so I think the best you can do is check the type at runtime, something like this:

    Edit: Based on David's comment, I've added the T: record constraint which can be used to constrain to value types (and rule out class types).

    type
      TConversions = class
      public
        class function StringToEnumeration(const S: string): T;
        class function EnumerationToString(Value: T): string;
      end;
    
    class function TConversions.EnumerationToString(Value: T): string;
    var
      P: PTypeInfo;
    begin
      P := PTypeInfo(TypeInfo(T));
      case P^.Kind of
        tkEnumeration:
          case GetTypeData(P)^.OrdType of
            otSByte, otUByte:
              Result := GetEnumName(P, PByte(@Value)^);
            otSWord, otUWord:
              Result := GetEnumName(P, PWord(@Value)^);
            otSLong, otULong:
              Result := GetEnumName(P, PCardinal(@Value)^);
          end;
        else
          raise EArgumentException.CreateFmt('Type %s is not enumeration', [P^.Name]);
      end;
    end;
    
    class function TConversions.StringToEnumeration(const S: string): T;
    var
      P: PTypeInfo;
    begin
      P := PTypeInfo(TypeInfo(T));
      case P^.Kind of
        tkEnumeration:
          case GetTypeData(P)^.OrdType of
            otSByte, otUByte:
              PByte(@Result)^ := GetEnumValue(P, S);
            otSWord, otUWord:
              PWord(@Result)^ := GetEnumValue(P, S);
            otSLong, otULong:
              PCardinal(@Result)^ := GetEnumValue(P, S);
          end;
        else
          raise EArgumentException.CreateFmt('Type %s is not enumeration', [P^.Name]);
      end;
    end;
    

提交回复
热议问题