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
Release: 2025-01-21 21:31:10
Original
706 people have browsed it

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:

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<动物>("大熊猫");
Copy after login

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