给枚举添加描述信息
1 namespace EnumDiscription
2 {
3
4 enum MyColors
5 {
6 [Description("红色的")]
7 Red = 1,
8
9 [Description("绿色的")]
10 Green = 2,
11
12 [Description("蓝色的")]
13 Yellow = 3,
14 }
15
16 class Program
17 {
18 static void Main(string[] args)
19 {
20 Console.WriteLine(GetDescription(MyColors.Red));//红色的
21 }
22
23 /// <summary>
24 /// 根据枚举得到描述信息
25 /// </summary>
26 /// <param name="value"></param>
27 /// <returns></returns>
28 public static string GetDescription(Enum value)
29 {
30 FieldInfo field = value.GetType().GetField(value.ToString());
31 DescriptionAttribute[] attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
32 return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
33 }
34 }
35