Enum-枚举的用法

孤者浪人 提交于 2020-01-28 23:06:31
    public enum BedType
        {
            [Description("单人床")]
            SINGLE = 1,
            [Description("大床")]
            DOUBLE = 2,
            [Description("上下铺")]
            BUNK = 3,
            [Description("通铺")]
            DORM_BED = 4,
            [Description("榻榻米")]
            TATAMI = 5,
            [Description("水床")]
            WATER_BED = 6,
            [Description("圆床")]
            ROUND_BED = 7,
            [Description("折叠床")]
            FOLDING_BED = 8,
            [Description("婴儿床")]
            BABY_COT = 9,
            [Description("拼床")]
            CONNECTED_BED = 10,
            [Description("其它")]
            OTHERS = 11
        }
       /// <summary>
        /// 返回描述值  例:同意  [Description("同意")]  
        /// </summary>
        /// <param name="source">Enum.Attribute</param>
        /// <returns>Description</returns>
        public static string GetDescription(Enum source)
        {
            var attr = GetAttribute<System.ComponentModel.DescriptionAttribute>(source);
            if (attr == null)
            {
                return null;
            }

            return attr.Description;
        }


        private static T GetAttribute<T>(Enum source) where T : Attribute
        {
            Type sourceType = source.GetType();
            string sourceName = Enum.GetName(sourceType, source);
            FieldInfo field = sourceType.GetField(sourceName);
            object[] attributes = field.GetCustomAttributes(typeof(T), false);
            foreach (object attribute in attributes)
            {
                if (attribute is T)
                {
                    return (T)attribute;
                }
            }
            return null;
        }
显示值//BABY_COT    
    EnumHelp.BedType.BABY_COT.ToString();
//9
    ((int)EnumHelp.BedType.BABY_COT).ToString();
//婴儿床
    EnumHelp.GetDescription(EnumHelp.BedType.BABY_COT);

//BUNK
    Enum.GetName(typeof(EnumHelp.BedType), 3);
//False
    Enum.IsDefined(typeof(EnumHelp.BedType), "ADD_REMARKS"); //BUNK       
EnumHelp.BedType SType = (EnumHelp.BedType)Enum.Parse(typeof(EnumHelp.BedType), "3", true);


 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!