c# - 通过描述属性查找枚举值

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

        }
    }
}

但是我对在那个内部 if 中做什么感到困惑。也不确定这是否是首先要走的路。

最佳答案

使用描述的扩展方法 here :

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

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

关于c# - 通过描述属性查找枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3422407/

相关文章:

c# - 如何解析 C# 泛型类型名称?

c# - 从抽象类引用继承的 EntitySet 的 dapper PropInfo Setter 为 null

java - ParameterizedType.getRawType() 返回 j.l.r.Type,而不是 Class<?>?

sqlite - SQLAlchemy、反射、不同的后端和表/列不区分大小写

java - 在 Java 中将特定枚举分配给 Class<Enum>

c# - Log4Net 不工作,但仅适用于发布控制台构建

c# - PDF 和 Silverlight,它们可以一起工作吗?

c# - 如何修改 IObservable<char> 以便我收集字符,直到一段时间内没有字符为止?

c# - ASP.NET MVC5 中的 JQuery UI 无法正常工作

java - 将 LambdaMetafactory.metafactory() 用于普通的非静态 getter