枚举定义,获取枚举的描述
Posted lhlong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了枚举定义,获取枚举的描述相关的知识,希望对你有一定的参考价值。
枚举定义,获取枚举的描述
定义枚举熟悉,描述
/// <summary> /// 枚举注释的自定义属性类 /// </summary> public class EnumDescriptionAttribute : Attribute { private string m_strDescription; public EnumDescriptionAttribute(string strPrinterName) { m_strDescription = strPrinterName; } public string Description { get { return m_strDescription; } } }
定义枚举
/// <summary> /// 日志登记区分 /// </summary> public enum LogLevel { /// <summary> /// 默认 /// </summary> [EnumDescription("正常")] Default = 0, /// <summary> /// 提醒 /// </summary> [EnumDescription("提醒")] Remind = 1, /// <summary> /// 崩溃 /// </summary> [EnumDescription("崩溃")] collapse = 2 }
获取枚举的描述
/// <summary> /// 获取枚举的描述信息 /// </summary> /// <typeparam name="T">枚举类型</typeparam> /// <param name="enums">枚举</param> /// <returns>枚举的描述,不存在则返回枚举的值</returns> public string GetEnumDescription<T>(object enums) { string RtnMsg = string.Empty; Dictionary<string, int> enumDic = new Dictionary<string, int>(); Type t = typeof(T); Array arrays = Enum.GetValues(t); for (int i = 0; i < arrays.LongLength; i++) { T test = (T)arrays.GetValue(i); if (test.ToString() == enums.ToString()) { try { FieldInfo fieldInfo = test.GetType().GetField(test.ToString()); object[] attribArray = fieldInfo.GetCustomAttributes(false); EnumDescriptionAttribute attrib = (EnumDescriptionAttribute)attribArray[0]; enumDic.Add(attrib.Description, DataConvert.GetValInt(test)); RtnMsg= attrib.Description; } catch (Exception) { RtnMsg = test.ToString(); } } } return RtnMsg; }
1087814
以上是关于枚举定义,获取枚举的描述的主要内容,如果未能解决你的问题,请参考以下文章