通过其描述属性查找枚举值

时间:2010-08-06 09:13:03

标签: c# reflection

这可能看起来有点颠倒,但我想要做的是通过其Description属性从枚举中获取枚举值。

所以,如果我有一个枚举声明如下:

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

我希望能够通过提供字符串“Peter Gouge”来获得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 个答案:

答案 0 :(得分:30)

使用here所述的扩展方法:

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

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

答案 1 :(得分:5)

return field.GetRawConstantValue();

如果需要,您当然可以将其重新投入测试。

答案 2 :(得分:2)

好的,在输入所有内容之后我认为这是一个决定的情况,一开始就让我走上了错误的道路。 Enum似乎是开始的正确方法,但简单的Dictionary<string, int>就足够了,并且更容易使用!