枚举一个不同的字符串

时间:2014-11-12 12:56:16

标签: c# .net vb.net

这个问题没有回答我的问题,因为我需要调用字符串,是否有可以添加的扩展方法?

我有一个Enum

public enum TimetableState
{
    ["Error Message"]
    errormessage = 0,
    Great = 1
}

我想再打电话

TimetableState.errormessage.ToString();

并在属性'错误消息'中显示字符串, 或者如果我调用Great.ToString()字符串' Great'归还。

属性可以是任何东西,它不必是描述。

我知道可以直接使用ToString(),但是怎么做?

+++++++ 这不是重复,因为我想通过在枚举上调用ToString()来获得相同的内容,因为我需要列表排序并显示以使用它。 这可能吗? ++++++++

1 个答案:

答案 0 :(得分:1)

更新: - 别介意我的回答,这是您正在寻找的内容:How to get C# Enum description from value?

我没有为它找到解决方案并且自己写了一个帮助函数:

    public static string GetDescription(Enum value)
    {
        string ret = value.ToString();
        FieldInfo fi = value.GetType().GetField(value.ToString());

        if (fi != null)
        {
            var att = fi.GetCustomAttribute<DescriptionAttribute>(true);

            if (att != null)
                ret = att.Description;
        }

        return ret;
    }

这是大约3年前,如果有一个内置的解决方案,我错过了或者现在有一个,我很乐意使用它。