zoukankan      html  css  js  c++  java
  • 枚举类型转换成字符串

    使用枚举类型默认的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

  • 相关阅读:
    phpExcel常用方法详解 F
    简单的图片变色方法 F
    TCP协议数据包及攻击分析
    你好世界
    团队项目 第一次作业
    NOIP提高组(2018)考试技巧及注意事项
    ACM常用模板数论
    ACM常用模板图论
    ACM常用模板数据结构
    I'm Coming
  • 原文地址:https://www.cnblogs.com/JustRun1983/p/2559073.html
Copyright © 2011-2022 走看看