字符串到枚举与描述 [英] String to Enum with Description

查看:84
本文介绍了字符串到枚举与描述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用基于这个建议。也就是说,我有一个与每个枚举元素相关联的描述属性。在该页面上,还有一个函数可以返回基于给定枚举的描述字符串。现在我想要实现的是相反的功能,也就是说,如果一个输入字符串查询枚举与相应的描述(如果存在),返回null,否则返回null。

I am currently implementing an associacion of strings and enums based on this suggestion. That being, I have a Description attribute associated with every enum element. On that page there is also a function which returns the description's string based on the given enum. What I would like to implement now is the reverse function, that is, given an input string lookup the enum with the corresponding description if it exists, returning null otherwise.

尝试(T)Enum.Parse(typeof(T),teststring)但它会引发异常。

推荐答案

你必须编写自己的反向方法。股票Parse()方法显然不了解你的描述属性。

You have to write your own reverse method. The stock Parse() method obviously doesn't know about your description attributes.

这样的东西应该可以工作:

Something like this should work:

public static T GetEnumValueFromDescription<T>(string description)
{
    MemberInfo[] fis = typeof(T).GetFields();

    foreach (var fi in fis)
    {
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0 && attributes[0].Description == description)
            return (T)Enum.Parse(typeof(T), fi.Name);
    }

    throw new Exception("Not found");
}

你会想要找一个更好的事情来抛出异常if但是没有找到枚举值。 :)

You'll want to find a better thing to do than throw an exception if the enum value wasn't found, though. :)

这篇关于字符串到枚举与描述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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