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>
Usage:
This method can be called as follows:
<code class="language-csharp">var panda = EnumEx.GetValueFromDescription<animal>("大熊猫");</code>
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!