根据描述属性获取枚举值
前面我们介绍过一个扩展方法,用于获取枚举关联的Description属性。现在,让我们探索一个补充函数,允许我们根据其描述获取枚举。
为此,我们引入以下扩展方法:
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); } }
使用方法:
此方法可以按如下方式调用:
var panda = EnumEx.GetValueFromDescription<animal>("大熊猫");
通过提供“大熊猫”描述,扩展方法将检索相应的大熊猫枚举值。
以上是如何从其描述属性中获取枚举值?的详细内容。更多信息请关注PHP中文网其他相关文章!