枚举类型转换成字符串

使用枚举类型默认的ToString()方法,往往不能得到我们想要的输出的字符串。
如何方便的定义枚举类型中的每个值代表的字符串输出呢?
可以使用DescriptionAttribute, 写上想得到的字符串输出。

复制代码
enum Direction
{
    [Description("Rover is facing to UP (Negtive Y)")]
    UP = 1,
    [Description("Rover is facing to DOWN (Positive Y)")]
    DOWN = 2,
    [Description("Rover is facing to RIGHT (Positive X)")]
    RIGHT = 3,
    [Description("Rover is facing to LEFT (Negtive X)")]
    LEFT = 4
}; 
复制代码

使用下面的方法,来得到对应项的字符串。

复制代码
/// <summary>
    /// Contains methods for working with <see cref="Enum"/>.
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// Gets the specified enum value's description.
        /// </summary>
        /// <param name="value">The enum value.</param>
        /// <returns>The description or <c>null</c>
        /// if enum value doesn't have <see cref="DescriptionAttribute"/>.</returns>
        public static string GetDescription(this Enum value)
        {
            var fieldInfo = value.GetType().GetField(value.ToString());
            var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(
                                                         typeof(DescriptionAttribute),
                                                         false);
            return attributes.Length > 0
                       ? attributes[0].Description
                       : null;
        }

        /// <summary>
        /// Gets the enum value by description.
        /// </summary>
        /// <typeparam name="EnumType">The enum type.</typeparam>
        /// <param name="description">The description.</param>
        /// <returns>The enum value.</returns>
        public static EnumType GetValueByDescription<EnumType>(string description)
        {
            var type = typeof(EnumType);
            if (!type.IsEnum)
                throw new ArgumentException("This method is destinated for enum types only.");
            foreach (var enumName in Enum.GetNames(type))
            {
                var enumValue = Enum.Parse(type, enumName);
                if (description == ((Enum)enumValue).GetDescription())
                    return (EnumType)enumValue;
            }
            throw new ArgumentException("There is no value with this description among specified enum type values.");
        }
    }
复制代码

 进一步了解.net中的Attribue


Creative Commons License

本文基于署名 2.5 中国大陆许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名justrun(包含链接)。如您有任何疑问或者授权方面的协商,请给我留言


本文转自JustRun博客园博客,原文链接:http://www.cnblogs.com/JustRun1983/archive/2012/06/22/2559073.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值