C# Enum Name String Description之间的相互转换
最近工作中经常用到Enum中Value、String、Description之间的相互转换,特此总结一下。
1.首先定义Enum对象
1 public enum Weekday 2 { 3 [Description("星期一")] 4 Monday=1, 5 [Description("星期二")] 6 Tuesday=2, 7 [Description("星期三")] 8 Wednesday=3, 9 [Description("星期四")] 10 Thursday=4, 11 [Description("星期五")] 12 Friday=5, 13 [Description("星期六")] 14 Saturday=6, 15 [Description("星期日")] 16 Sunday=7 17 }
2.根据string类型的值,获取相应的对象,例如:“Sunday”获取Weekday.Sunday.
1 public static Weekday GetEnumFromString(string str) 2 { 3 Weekday week; 4 bool b = Enum.TryParse(str, true, out week); 5 if (b) 6 return week; 7 else 8 throw new Exception("没有找到对应的Enum"); 9 }
3.根据Value类型的值,获取对应的description。
1 public static String GetEnumDescription(Weekday week) 2 { 3 4 FieldInfo field = week.GetType().GetField(week.ToString()); 5 object[] obj = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 6 DescriptionAttribute da; 7 if (obj != null && obj.Length > 0) 8 { 9 da = (System.ComponentModel.DescriptionAttribute)obj[0]; 10 return da.Description; 11 } 12 else 13 throw new Exception("没有找到对应的Description"); 14 }
4.根据Description的值,获取对应的Value。
1 public static Weekday GetEnumFromDescription(string description) 2 { 3 foreach(Weekday week in Enum.GetValues(typeof(Weekday))) 4 { 5 if (description.Equals(GetEnumDescription(week))==true) 6 return week; 7 } 8 throw new Exception("没有找到对应的Enum"); 9 }