2018年6月20日
[C#]枚举类型定义错误码和获取描述信息
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.ComponentModel; using System.ServiceModel; using System.ServiceModel.Web; using System.Runtime.Serialization; using System.IO; namespace MyLibrary { public enum ErrorCode { [Description("成功")] Success = 0, [Description("未知错误")] Failed = 1, [Description("服务暂不可用")] NoService = 2, [Description("未知方法")] UnsupportedMethod = 3, [Description("请求参数无效")] InvalidParameter = 4, [Description("读取配置文件出错")] ReadConfigFailed = 5, [Description("数据库连接出错")] DBConectionFailed = 6 } public class CommonUtils { /// <summary> /// 获取枚举项描述信息 例如GetEnumDesc(Days.Sunday) /// </summary> /// <param name="en">枚举项 如Days.Sunday</param> /// <returns></returns> public static string GetEnumDesc(Enum en) { Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) { return ((DescriptionAttribute)attrs[0]).Description; } } return en.ToString(); } } }