zoukankan      html  css  js  c++  java
  • 利用DescriptionAttribute实现枚举字符串

    我们知道定义枚举时是不允许带空格等符号的,这样就不利于进行字符串对比。当然可以通过给枚举添加DescriptionAttribute,然后通过fieldinfo读取DescriptionAttribute来获取字符串。

    以下是例子

    先定义枚举

        /// <summary>
        /// Campaign Mode
        /// </summary>
        public enum CampaignModeEnum
        {
            /// <summary>
            /// Inbound
            /// </summary>
            [DescriptionAttribute("Inbound")]
            Inbound,
            /// <summary>
            /// Outbound Preview
            /// </summary>
            [DescriptionAttribute("Outbound Preview")]
            Outbound_Preview,
            /// <summary>
            /// Outbound Predictive
            /// </summary>
            [DescriptionAttribute("Outbound Predictive")]
            Outbound_Predictive
        }
    

    编写获取DescriptionAttribute的类

        public static class EnumMethod
        {
            public static string StringValue(Enum value)
            {
                FieldInfo fi = value.GetType().GetField(value.ToString());
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
                else
                {
                    return value.ToString();
                }
            }
        }
    

      

    这样调用就可以啦!

    EnumMethod.StringValue(CampaignModeEnum.Outbound_Predictive);

      

  • 相关阅读:
    ReentrantLock与synchronized的差别
    读TIJ -1 对象入门
    wikioi 2573 大顶堆与小顶堆并用
    开源 免费 java CMS
    UVA10972
    springboot5
    spring-boot4
    spring-boot3
    spring-boot2
    spring-boot1
  • 原文地址:https://www.cnblogs.com/colder/p/3532135.html
Copyright © 2011-2022 走看看