Home > Backend Development > C++ > How to Convert an Enum Description Back to its Enum Value?

How to Convert an Enum Description Back to its Enum Value?

DDD
Release: 2025-01-21 21:37:10
Original
609 people have browsed it

How to Convert an Enum Description Back to its Enum Value?

Convert from enum description back to enum value

In each case, the enumeration value needs to be retrieved based on the enumeration's associated description properties. Let's explore a general approach to achieve this.

Consider the following example where we have an extension method to get the description property of an enum:

<code>public static string GetDescription(this Enum value)
{
    // 获取Description属性的实现
}</code>
Copy after login

Using this method, we can get the description by calling the following code:

<code>string myAnimal = Animal.GiantPanda.GetDescription(); // "Giant Panda"</code>
Copy after login

Now, let’s dive into the reverse process of converting a description attribute back to its corresponding enumeration value. For this purpose, we introduce a helper method:

<code>public static T GetValueFromDescription<T>(string description) where T : Enum
{
    // 根据描述检索枚举值的实现
}</code>
Copy after login

In this method, we iterate over the fields of the enumeration type and use reflection to retrieve their DescriptionAttributes:

<code>foreach (var field in typeof(T).GetFields())
{
    // 检查DescriptionAttribute并与提供的描述匹配的逻辑
}</code>
Copy after login

We can use the field name as a fallback mechanism if no matching DescriptionAttribute is found. Finally, we cast the result to the desired enum type:

<code>return (T)field.GetValue(null);</code>
Copy after login

To use this method, simply specify the enumeration type and description properties:

<code>var panda = EnumEx.GetValueFromDescription<Animal>("Giant Panda");</code>
Copy after login

The above is the detailed content of How to Convert an Enum Description Back to its Enum Value?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template