获取枚举类型描述
代码修改前:
switch (months) { case "1": nums = "1"; break; case "2": nums = "2"; break; case "3": nums = "3"; break; case "4": nums = "4"; break; case "5": nums = "5"; break; case "6": nums = "6"; break; case "7": nums = "7"; break; case "8": nums = "8"; break; case "9": nums = "9"; break; case "10": nums = "A"; break; case "11": nums = "B"; break; case "12": nums = "C"; break; }
代码修改后:
class Program { static void Main(string[] args) { Console.WriteLine(GetMonth("1")); Console.WriteLine(GetMonth("10")); Console.ReadKey(); } public static string GetMonth(string month) { var enumValue = (month)Enum.Parse(typeof(month), month); var enumAttributes = enumValue.GetType().GetField(enumValue.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false); var attributeValue = ((DescriptionAttribute[])enumAttributes)[0].Description; return attributeValue; } } public enum month { [Description("1")] Jan=1, [Description("2")] Feb =2, [Description("3")] Mar =3, [Description("4")] Apr =4, [Description("5")] May =5, [Description("6")] Jun =6, [Description("7")] Jul =7, [Description("8")] Aug =8, [Description("9")] Sep =9, [Description("A")] Oct =10, [Description("B")] Nov =11, [Description("C")] Dec =12 }