代码之家  ›  专栏  ›  技术社区  ›  DavidGouge

通过其描述属性[重复]查找枚举值

  •  25
  • DavidGouge  · 技术社区  · 15 年前

    这个问题已经有了答案:

    这看起来有点颠倒,但我希望能够通过一个枚举的description属性从该枚举中获取一个枚举值。

    因此,如果我有一个枚举声明如下:

    enum Testing
    {
        [Description("David Gouge")]
        Dave = 1,
        [Description("Peter Gouge")]
        Pete = 2,
        [Description("Marie Gouge")]
        Ree = 3
    }
    

    我想通过提供“彼得·戈夫”这根绳子来取回2根。

    作为起点,我可以迭代枚举字段并使用正确的属性获取字段:

    string descriptionToMatch = "Peter Gouge";
    FieldInfo[] fields = typeof(Testing).GetFields();
    
    foreach (FieldInfo field in fields)
    {
        if (field.GetCustomAttributes(typeof(DescriptionAttribute), false).Count() > 0)
        {
            if (((DescriptionAttribute)field.GetCustomAttributes(typeof(DescriptionAttribute), false)[0]).Description == descriptionToMatch)
            {
    
            }
        }
    }
    

    但后来我就一直在想,在内心深处该怎么做。也不确定这是不是一开始就要走的路。

    3 回复  |  直到 12 年前
        1
  •  30
  •   Community CDub    8 年前

    使用描述的扩展方法 here :

    Testing t = Enum.GetValues(typeof(Testing))
                    .Cast<Testing>()
                    .FirstOrDefault(v => v.GetDescription() == descriptionToMatch);
    

    如果找不到匹配的值,它将返回 (Testing)0 (您可能需要定义 None 枚举中此值的成员)

        2
  •  4
  •   Ani    15 年前
    return field.GetRawConstantValue();
    

    当然,如果需要的话,您可以将其转换回测试。

        3
  •  1
  •   DavidGouge    15 年前

    好吧,在输入了所有我认为这是一个决定的案例,从一开始就引导我走上了错误的道路。Enum似乎是正确的开始方法,但是 Dictionary<string, int> 就够了,工作起来容易多了!