Enum-枚举的用法
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; }
/// <summary>
/// 根据属性获取对应枚举 有默认值
/// 单此description不存在 默认值为最小的枚举值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="description"></param>
/// <returns>对应枚举值</returns>
public static T GetEnumByDescription<T>(string description)
{
FieldInfo[] fields = typeof(T).GetFields();
foreach (FieldInfo field in fields)
{
object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性
if (objs.Length > 0 && (objs[0] as DescriptionAttribute).Description == description)
{
return (T)field.GetValue(null);
}
}
return default(T);
}
显示值
//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);