通过其描述属性查找枚举值 [英] Finding an enum value by its Description Attribute

查看:18
本文介绍了通过其描述属性查找枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This may seem a little upside down faced, but what I want to be able to do is get an enum value from an enum by its Description attribute.

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

So, if I have an enum declared as follows:

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

我希望能够通过提供字符串Peter Gouge"来取回 2.

I'd like to be able to get 2 back by supplying the string "Peter Gouge".

作为起点,我可以遍历枚举字段并获取具有正确属性的字段:

As a starting point, I can iterate through the enum fields and grab the field with the correct attribute:

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)
        {

        }
    }
}

但后来我被困在那个内部如果做什么.也不确定这是不是首先要走的路.

But then I'm stuck as to what to do in that inner if. Also not sure if this is the way to go in the first place.

推荐答案

使用描述的扩展方法 这里 :

Using the extension method described here :

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

如果没有找到匹配的值,它将返回 (Testing)0(你可能想在你的枚举中为这个值定义一个 None 成员)

If no matching value is found, it will return (Testing)0 (you might want to define a None member in your enum for this value)

这篇关于通过其描述属性查找枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆