AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79376251
Accepted
Arthur Araujo
Arthur Araujo
Asked: 2025-01-22 08:22:37 +0800 CST2025-01-22 08:22:37 +0800 CST 2025-01-22 08:22:37 +0800 CST

É possível recuperar atributos para um valor Enum no Delphi 12?

  • 772

Se eu tiver um tipo Enum como este:

  TOAuthSubjectTypes = (
    [MappingAttr('public')]
    ostPublic,
    [MappingAttr('pairwise')]
    ostPairwise
  );

E em um dado momento eu tenho uma variável que contém ostPairwise, é possível recuperar o atributo para o valor ostPairwise? No momento, a solução alternativa que estou aplicando é definir todos os atributos em ordem para o tipo Enum e alcançá-los por meio GetAttributesdo valor Ordinal do tipo enum, mas eu me pergunto se há uma maneira mais idiomática.

Desculpe se estiver duplicado. Encontrei muitas respostas nas tags de idiomas de outros, mas nada relacionado nas do Delphi.

delphi
  • 2 2 respostas
  • 91 Views

2 respostas

  • Voted
  1. Best Answer
    Remy Lebeau
    2025-01-22T09:45:19+08:002025-01-22T09:45:19+08:00

    Infelizmente, não há como fazer o que você quer, pois não há RTTI armazenado para membros de enumeração individuais, apenas para o tipo de enumeração em si.

    De acordo com esta resposta ao Delphi 2010 RTTI: Explore Enumerations (que ainda é válido para o Delphi 12):

    Atributos associados a elementos em enumerações não são armazenados atualmente em dados RTTI do Win32 no executável. O RTTI já é responsável por um aumento justo no tamanho dos executáveis, então algumas linhas tiveram que ser desenhadas em algum lugar. Atributos no Delphi Win32 são suportados em tipos, em campos de registros e campos, métodos, seus parâmetros e propriedades de classes.

    As declarações de atributos não causam erros devido à compatibilidade com versões anteriores do Delphi para .NET.

    Então, sua solução alternativa para colocar os atributos no tipo enum e então indexá-los pelo valor enum é a melhor que você pode fazer.

    • 3
  2. Arthur Araujo
    2025-01-22T12:14:53+08:002025-01-22T12:14:53+08:00

    Seguindo a resposta de Remy, parece não ser possível acessar Atributos de membros específicos. A maneira como consegui um resultado semelhante foi definindo um atributo como:

      MappingAttr = class(TCustomAttribute)
      private
        FValue: String;
      public
        constructor Create(const AValue: string);
        property Value: string read FValue;
      end;
    

    E duas funções genéricas, declaradas como

      ///  <summary>
      ///   Class to hold generic functions that deal with conversion between Strings
      ///  and Mapping Enums.
      ///  </summary>
      TEnumMapping = class
      public
      ///  <summary>
      ///  Takes an enumeration value and returuns the value of the <see cref="MappingAttr"/> for that entry
      ///  </summary>
      ///  <param name="Value"><i>T</i>: Type of the enum used.</param>
        class function EnumToString<T>(const Value: T): string; static;
      ///  <summary>
      ///  Takes a string value and returns the enumeration value (index) related to that string.
      ///  For it to work there are some assumptions that will lead to exceptions if ignored, (or worse, UB)
      ///
      ///  1. The Enum has the same amount of attributes and items. (For each enumerated name there is one and only one attribute AND it has a MappingAttr type)
      ///  2. The Enum has no custom ordinality.
      ///  3. The type of the attribute mapping the Enum is MappingAttr.
      ///  </summary>
      ///
      ///
        class function StringToEnum<T>(const Value: string): T; static;
      end;
    

    E implementado como

    
    class function TEnumMapping.EnumToString<T>(const Value: T): string;
    var
      RTTICtx: TRttiContext;
      RTTIType: TRttiType;
      RTTIEnum: TRttiEnumerationType;
      GenericValue: TValue;
      OrdValue: Int64;
    begin
      RTTICtx := TRTTIContext.Create;
      try
        RTTIType := RTTICtx.GetType(TypeInfo(T));
        // Raises an exception if the type is not an enumeration.
        if (RTTIType = nil) then
          raise ETypeHasNoRTI.Create('The type has no Runtime Information');
    
        if (RTTIType.TypeKind <> tkEnumeration) then
          raise Exception.CreateFmt('Type %s is not an enumeration', [RttiType.Name]);
    
        // Creates a TValue from Value and try casting it to Ordinal
        GenericValue := TValue.From<T>(Value);
        if not GenericValue.TryAsOrdinal(OrdValue) then
          raise EInvalidCast.Create('Could not cast generic value to ordinal');
    
        RTTIEnum := TRTTIEnumerationType(RTTIType);
        if (OrdValue > RTTIEnum.MaxValue) or (OrdValue < RTTIEnum.MinValue) then
          raise EEnumNameNotFound.CreateFmt('%d has no valid enum name for %s', [OrdValue, RTTIType.Name]);
    
        var LenStore: Integer := Length(RTTIEnum.GetAttributes);
        if (LenStore = 0) or (LenStore - 1 < OrdValue) then
          raise ERTTIMappingBadFormat.CreateFmt('RTTI Mapping in %s is badly formated.', [RTTIEnum.Name]);
    
        exit(MappingAttr(RTTIEnum.GetAttributes()[OrdValue]).Value);
      finally
        RTTICtx.Free;
      end;
    
      raise ERTTIMappingNotFound.Create('No [MappingAttr(...)] found');
    end;
    
    class function TEnumMapping.StringToEnum<T>(const Value: string): T;
    var
      RTTICtx: TRTTIContext;
      RTTIType: TRTTIType;
    begin
      RTTICtx := TRTTIContext.Create();
      try
        RTTIType := RTTICtx.GetType(TypeInfo(T));
        // Raises an exception if the type is not an enumeration.
        if (RTTIType = nil) or (RTTIType.TypeKind <> tkEnumeration) then
          raise Exception.CreateFmt('Type %s is not an enumeration', [RttiType.Name]);
    
        FillChar(Result, SizeOf(Result), 0); // Set a default value
    
        var ItemCount, AttrCount: Integer;
        ItemCount := Length(TRTTIEnumerationType(RTTIType).GetNames());
        AttrCount := Length(RTTIType.GetAttributes());
    
        if (AttrCount = 0) or (ItemCount <> AttrCount) then // No Attr or different amounts
          raise ERTTIMappingBadFormat.CreateFmt('RTTI Mapping in %s is badly formated.', [RTTIType.Name]);
    
        var Index: Integer := 0;
        var Walks: Integer := 0;
        var Found: Boolean := False;
        for var Attr: TCustomAttribute in RTTIType.GetAttributes do
        begin
          if Attr is MappingAttr then // just in case. Should always be MappingAttr.
          begin
            Inc(Index);
            Found := MappingAttr(Attr).Value = Value;
            if Found then // Will break if the attribute value matches the search.
              break;
          end;
        end;
    
        if not Found then
          raise ERTTIMappingNotFound.CreateFmt('No match for %s on %s', [Value, RTTIType.Name]);
    
        // Casts the address of result to a integer pointer, deref it, assigns Index.
        PInteger(@Result)^ := Index; // if not frend why frend shaped?
        Exit(Result);
      finally
        RTTICtx.Free();
      end;
    
      raise Exception.Create('Something went *very* wrong.');
    end;
    

    Elas foram escritas às pressas, mas funcionaram até agora. O problema é definir todos os atributos em relação ao tipo Enum e não seus valores, então, enquanto as suposições antes das funções se mantiverem, ele será capaz de recuperar consistentemente, eu acho.

    • 0

relate perguntas

  • Como removo a mensagem “versão de teste não licenciada” em um projeto TMS Web Core? [fechado]

  • Por que TIdHTTP.Head() está gerando uma exceção 'HTTP/1.1 406 Not Acceptable'?

  • TTreeView: como marcar/desmarcar SOMENTE filhos de um TTreeNode?

  • Como pesquisar a partir da posição onde o cursor está no momento?

  • Usando a linguagem Rust no Delphi/RAD Studio/C++ Builder? [fechado]

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve