Home > Backend Development > C++ > How to Retrieve Enumeration Values from Description Attributes in C#?

How to Retrieve Enumeration Values from Description Attributes in C#?

Linda Hamilton
Release: 2025-01-21 21:41:13
Original
562 people have browsed it

How to Retrieve Enumeration Values from Description Attributes in C#?

Retrieve enumeration value based on description attribute

In some programming scenarios, it is necessary to retrieve the enumeration value based on the description attribute associated with the enumeration. This is especially useful when working with enumerations that have descriptive labels.

can be achieved using the Enum.GetValueFromDescription() method. However, this method does not exist in the .NET Framework. We can implement a custom extension method to make up for this shortcoming. The following code snippet demonstrates such an implementation:

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);
    }
}
Copy after login

How to use:

var panda = EnumEx.GetValueFromDescription<animal>("大熊猫");
Copy after login

By calling the GetValueFromDescription method you can retrieve the enumeration value corresponding to the specified description property. This method iterates over the enumeration's fields, checking the DescriptionAttribute attributes and returning the corresponding value if there is a match. If no matching description is found, an exception is thrown or the default value of the enum type is returned, depending on the implementation.

The above is the detailed content of How to Retrieve Enumeration Values from Description Attributes in C#?. For more information, please follow other related articles on the PHP Chinese website!

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