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); } }
How to use:
var panda = EnumEx.GetValueFromDescription<动物>("大熊猫");
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!