为了账号安全,请及时绑定邮箱和手机立即绑定

从描述属性获取Enum

从描述属性获取Enum

MM们 2019-07-10 10:22:33
从描述属性获取Enum我有一个泛型扩展方法,它获取Description属性的Enum:enum Animal{     [Description("")]     NotSet = 0,     [Description("Giant Panda")]     GiantPanda = 1,     [Description("Lesser Spotted Anteater")]     LesserSpottedAnteater = 2}public static string GetDescription(this Enum value){                 FieldInfo field = value.GetType().GetField(value.ToString());     DescriptionAttribute attribute            = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute))                 as DescriptionAttribute;     return attribute == null ? value.ToString() : attribute.Description;}所以我可以.。string myAnimal = Animal.GiantPanda.GetDescription(); // = "Giant Panda"现在,我试着在另一个方向上计算出等价的函数,就像.Animal a = (Animal)Enum.GetValueFromDescription("Giant Panda", typeof(Animal));
查看完整描述

3 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

与其使用扩展方法,不如尝试一些静态方法。

public static class Utility{
    public static string GetDescriptionFromEnumValue(Enum value)
    {
        DescriptionAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof (DescriptionAttribute), false)
            .SingleOrDefault() as DescriptionAttribute;
        return attribute == null ? value.ToString() : attribute.Description;
    }

    public static T GetEnumValueFromDescription<T>(string description)
    {
        var type = typeof(T);
        if (!type.IsEnum)
            throw new ArgumentException();
        FieldInfo[] fields = type.GetFields();
        var field = fields                        .SelectMany(f => f.GetCustomAttributes(
                            typeof(DescriptionAttribute), false), (
                                f, a) => new { Field = f, Att = a })
                        .Where(a => ((DescriptionAttribute)a.Att)
                            .Description == description).SingleOrDefault();
        return field == null ? default(T) : (T)field.Field.GetRawConstantValue();
    }}

在这里使用

var result1 = Utility.GetDescriptionFromEnumValue(
    Animal.GiantPanda);var result2 = Utility.GetEnumValueFromDescription<Animal>(
    "Lesser Spotted Anteater");


查看完整回答
反对 回复 2019-07-10
  • 3 回答
  • 0 关注
  • 585 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信