c# - 带描述的枚举字符串

标签 c# enums

我目前正在实现基于 this suggestion 的字符串和枚举的关联.也就是说,我有一个与每个枚举元素关联的 Description 属性。在那个页面上还有一个函数,它根据给定的枚举返回描述的字符串。我现在想实现的是反向函数,即给定一个输入字符串查找具有相应描述的枚举(如果存在),否则返回 null。

我试过 (T) Enum.Parse(typeof(T), "teststring") 但它抛出异常。

最佳答案

你必须自己编写反向方法。常用的 Parse() 方法显然不知道您的描述属性。

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

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");
}

不过,如果找不到枚举值,您会想找到比抛出异常更好的方法。 :)

关于c# - 带描述的枚举字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4249632/

相关文章:

c# - 是否可以创建分层枚举?

Java 从枚举中检索数据

c# - 我应该在执行 SQL 语句之前从中删除空格吗?

c# - 向数据库中插入值

c# - 如何查明 WebClient.DownloadFileTaskAsync 是否已取消?

c# - 如何对实例变量使用惰性

c# - Enum.GetValues 中的意外行为或传递 Enums

c++ - 我可以在枚举中使用枚举吗?

java - 如何将 String 转换为正确的 Enum 常量(实现公共(public)接口(interface)的多个 Enum)?

c# - 使用 LINQ to SQL 记录更改