一、声明枚举值、枚举值描述
using ponentModel;public enum status{/// <summary>/// 取消/// </summary>[Description("取消")]cancel,/// <summary>/// 提交/// </summary>[Description("提交")]submit,/// <summary>/// 同意/// </summary>[Description("批准")]pass,/// <summary>/// 驳回/// </summary>[Description("驳回")]reject}
二、获取枚举值字符串、根据枚举获取枚举值描述
/// <summary>/// 获取枚举描述信息/// </summary>/// <param name="enumValue"></param>/// <returns></returns>public static string GetEnumDescription(this Enum enumValue) {string str = enumValue.ToString();System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);object[] objs = field.GetCustomAttributes(typeof(ponentModel.DescriptionAttribute) , false);if (objs == null || objs.Length == 0)return str;ponentModel.DescriptionAttribute da = (ponentModel.DescriptionAttribute)objs[0];return da.Description;}/*示例:string statusDes = status.submit.GetEnumDescription();*//// <summary>/// 枚举字符串/// </summary>/// <typeparam name="T"></typeparam>/// <param name="enumValue"></param>/// <returns></returns>public static string GetEnumString<T>(this Enum enumValue) {return Enum.GetName(typeof(T) , enumValue);//推荐 }/*示例:string status = status.submit.GetEnumString<status>();*//// <summary>/// 根据Description获取枚举/// </summary>/// <typeparam name="T">枚举类型</typeparam>/// <param name="description">枚举描述</param>/// <returns>枚举</returns>public static string GetEnumName<T>(string description){Type _type = typeof(T);foreach (FieldInfo field in _type.GetFields()){DescriptionAttribute[] _curDesc = field.GetDescriptAttr();if (_curDesc != null && _curDesc.Length > 0){if (_curDesc[0].Description == description)return field.GetValue(null).ToString();}}return null;}/*示例:string status = GetEnumName<status>("提交");*/
三、根据枚举值变量获取枚举描述信息
status statusEnum;//方式1Enum.TryParse<status>(strStatus, out statusEnum);//方式2statusEnum = (status)Enum.Parse(typeof(status), strStatus);string strStatusDes = statusEnum.GetEnumDescription();
如果觉得《C# 声明枚举 枚举值描述 获取枚举值字符串 根据枚举获取枚举值描述》对你有帮助,请点赞、收藏,并留下你的观点哦!