枚举(enum)加特性,取特性中的备注
public enum MsgCodeEnum { /// <summary> /// 操作成功 /// </summary> [Display(Name = "Success!", Description = "操作成功")] Success = 0, /// <summary> /// 未知错误 /// </summary> [Display(Name = "Undefined Error!", Description = "未知错误")] Failed = 1, /// <summary> /// 服务暂不可用 /// </summary> [Display(Name = "Service Not Avaliable!", Description = "服务暂不可用")] NoService = 2, /// <summary> /// 未知方法 /// </summary> [Display(Name = "Undefined Method", Description = "未知方法")] UnsupportedMethod = 3, } /// <summary> /// 语言类型 /// </summary> public enum LanguageEnum { En = 0, Cn = 1 } /// <summary> /// 中英文信息模型 /// </summary> public class MsgInfo { public string En { get; set; } public string Cn { get; set; } public MsgInfo(string en, string cn) { En = en; Cn = cn; } } public class EnumUtils { /// <summary> /// 根据枚举获取中英文信息 /// </summary> /// <param name="en"></param> /// <param name="languageType"></param> /// <returns></returns> public static string GetEnumDesc(MsgCodeEnum en, int languageType = (int)LanguageEnum.Cn) { Type type = en.GetType(); var disName = type.GetField(en.ToString()); //display名字 var name = (DisplayAttribute)disName.GetCustomAttribute(typeof(DisplayAttribute)); if (languageType == (int)LanguageEnum.Cn) { return name.Description ?? ""; } return name.Name ?? ""; } /// <summary> /// 根据枚举code获取中英文信息 /// </summary> /// <param name="en"></param> /// <returns></returns> public static MsgInfo GetEnumDescAll(MsgCodeEnum en) { Type type = en.GetType(); var disName = type.GetField(en.ToString()); //display名字 var name = (DisplayAttribute)disName.GetCustomAttribute(typeof(DisplayAttribute)); MsgInfo msg = new MsgInfo(name.Description, name.Name); return msg; } }