How can I call GetEnumName with a generic enumerated type?

后端 未结 2 1148
小鲜肉
小鲜肉 2021-01-05 08:54

I have a Generic class wich uses an Enum Generic Type. My problem how do I use GetEnumName on an instance of that type ?

I\'ve created a small demo class to illustra

2条回答
  •  无人及你
    2021-01-05 09:17

    This is an updated version af my class, with the change suggested. Thanks to David and TLama

    uses
      TypInfo, Rtti;
    
    type
      TEnumSettings = class
      private
        Key: TKey;
      public
        constructor Create(aKey: TKey);
        function ToString: string; override;
      end;
    
    
    { TEnumSettings }
    
    constructor TEnumSettings.Create(aKey: TKey);
    begin
      if PTypeInfo(System.TypeInfo(TKey)).Kind <> tkEnumeration then
        raise Exception.Create(string(PTypeInfo(System.TypeInfo(TKey)).Name) + ' is not an Enumeration');
      Key := aKey;
    end;
    
    function TEnumSettings.ToString: string;
    begin
      Result := TValue.From(Key).ToString;
    end;
    

    And a little test example :

    Copy the code into OnCreate of a From:

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      with TEnumSettings .Create(True) do
        try
          Caption := ToString;
        finally
          Free;
        end;
    end;
    

提交回复
热议问题