Home >Backend Development >C++ >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:
<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<animal>("大熊猫");</code>
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!