字符串到枚举说明

Mig*_*uel 10 c# enums

我目前正在根据这个建议实现字符串和枚举的关联.就是这样,我有一个Description与每个枚举元素相关联的属性.在该页面上还有一个函数,它根据给定的枚举返回描述的字符串.我现在要实现的是反向函数,也就是说,给定一个输入字符串查找带有相应描述的枚举(如果存在),否则返回null.

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

Ada*_*ear 17

你必须编写自己的反向方法.库存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");
}
Run Code Online (Sandbox Code Playgroud)

如果没有找到枚举值,你会想要找到一个更好的事情,而不是抛出异常.:)