Home > Backend Development > C++ > How Can I Get an Enum Value from its Description Attribute?

How Can I Get an Enum Value from its Description Attribute?

Patricia Arquette
Release: 2025-01-21 21:28:10
Original
572 people have browsed it

How Can I Get an Enum Value from its Description Attribute?

Get the enumeration value based on the description attribute

We introduced an extension method earlier, which is used to obtain the Description attribute associated with the enumeration. Now, let's explore a complementary function that allows us to obtain an enumeration based on its description.

To do this, we introduce the following extension methods:

<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>
Copy after login

Usage:

This method can be called as follows:

<code class="language-csharp">var panda = EnumEx.GetValueFromDescription<animal>("大熊猫");</code>
Copy after login

By providing a "pandas" description, the extension method will retrieve the corresponding pandas enumeration value.

The above is the detailed content of How Can I Get an Enum Value from its Description Attribute?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template