Home >Backend Development >C++ >How Can I Reverse Lookup an Enum Value Using Its Description Attribute?

How Can I Reverse Lookup an Enum Value Using Its Description Attribute?

Susan Sarandon
Susan SarandonOriginal
2025-01-21 21:31:10710browse

How Can I Reverse Lookup an Enum Value Using Its Description Attribute?

Look up the enumeration value reversely through the description attribute

In addition to getting the Description property from the enumeration, you can also perform the reverse operation and retrieve the enumeration value based on its Description property.

To do this, create a generic extension method called GetValueFromDescription as follows:

<code class="language-csharp">public static class EnumEx
{
    public static T GetValueFromDescription<T>(string description) where T : Enum
    {
        foreach (var field in typeof(T).GetFields())
        {
            if (Attribute.GetCustomAttribute(field,
            typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
            {
                if (attribute.Description == description)
                    return (T)field.GetValue(null);
            }
            else
            {
                if (field.Name == description)
                    return (T)field.GetValue(null);
            }
        }

        throw new ArgumentException("未找到。", nameof(description));
        // 或者返回 default(T);
    }
}</code>

How to use:

<code class="language-csharp">var panda = EnumEx.GetValueFromDescription<动物>("大熊猫");</code>

The above is the detailed content of How Can I Reverse Lookup an Enum Value Using Its Description Attribute?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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