📅  最后修改于: 2022-03-11 14:48:43.786000             🧑  作者: Mango
public static class EnumEx
{
public static T GetValueFromDescription(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("Not found.", nameof(description));
// Or return default(T);
}
}
var panda = EnumEx.GetValueFromDescription("Giant Panda");