标签:枚举 eof throw foreach course object tom return col
/// <summary> /// 根据描述获取枚举值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="description"></param> /// <returns></returns> public static T GetEnumByDescription<T>(string description) where T : Enum { System.Reflection.FieldInfo[] fields = typeof(T).GetFields(); foreach (System.Reflection.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); } } throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description"); }
根据描述获取枚举
/// <summary> /// 根据枚举值,获取描述 /// </summary> /// <param name="enumValue"></param> /// <returns></returns> public static string GetEnumDes(Enum enumValue) { string value = enumValue.ToString(); FieldInfo field = enumValue.GetType().GetField(value); object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false); //获取描述属性 if (objs == null || objs.Length == 0) //当描述属性没有时,直接返回名称 return value; DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0]; return descriptionAttribute.Description; }
根据枚举返回描述
namespace zxx { /// <summary> /// 订单类型 /// </summary> public enum OrderType { /// <summary> /// 订金 /// </summary> [Description("订金")] Pre, /// <summary> /// 学费 /// </summary> [Description("学费")] TutionFee, /// <summary> /// 课程费差价 /// </summary> [Description("课程费差价")] CourseFee, /// <summary> /// 附加服务 /// </summary> [Description("附加服务")] Addtional, /// <summary> /// 成绩单 /// </summary> [Description("成绩单")] Transcript, } }
标签:枚举 eof throw foreach course object tom return col
原文地址:https://www.cnblogs.com/gzbit-zxx/p/13877065.html