其他擴展方法詳見:https://www.cnblogs.com/zhuanjiao/p/12060937.html
/// <summary> /// 擴展方法,獲得枚舉的Description /// </summary> /// <param name="value">枚舉值</param> /// <param name="nameInstead">當枚舉值沒有定義DescriptionAttribute,是否使用枚舉名代替,默認是使用</param> /// <returns>枚舉的Description</returns> public static string GetDescription(this Enum value, Boolean nameInstead = true) { Type type = value.GetType(); string name = Enum.GetName(type, value); if (name == null) { return null; } FieldInfo field = type.GetField(name); DescriptionAttribute attribute = System.Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && nameInstead == true) { return name; } return attribute?.Description; }
隨便整一個枚舉
public enum ModuleType { /// <summary> /// 中國 /// </summary> [Description("中國")] ZH = 1, /// <summary> /// 美國 /// </summary> [Description("美國")] MG = 2 }
舉例 :var AppId = ModuleType.ZH.GetDescription() // 得到“中國”