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);
来源:https://www.cnblogs.com/Harvard-L/p/6042866.html