枚举的ToString具有用户友好的字符串 [英] Enum ToString with user friendly strings

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

问题描述

我的枚举包括以下值:

private enum PublishStatusses{
    NotCompleted,
    Completed,
    Error
};

我希望能够输出虽然一个用户友好的方式这些值。结果
我并不需要能够从串去再次值。

I want to be able to output these values in a user friendly way though.
I don't need to be able to go from string to value again.

推荐答案

我使用<$c$c>Description从System.ComponentModel命名空间属性。简单地装点枚举:

I use the Description attribute from the System.ComponentModel namespace. Simply decorate the enum:

private enum PublishStatusValue
{
    [Description("Not Completed")]
    NotCompleted,
    Completed,
    Error
};

然后用这个code找回它:

Then use this code to retrieve it:

public static string GetDescription<T>(this T enumerationValue)
            where T : struct
        {
            Type type = enumerationValue.GetType();
            if (!type.IsEnum)
            {
                throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");
            }

            //Tries to find a DescriptionAttribute for a potential friendly name
            //for the enum
            MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
            if (memberInfo != null && memberInfo.Length > 0)
            {
                object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0)
                {
                    //Pull out the description value
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }
            //If we have no description attribute, just return the ToString of the enum
            return enumerationValue.ToString();

        }

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

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