枚举扩展方法
 1  /// <summary>
 2         /// 扩展方法,获得枚举的Description
 3         /// </summary>
 4         /// <param name="value">枚举值</param>
 5         /// <param name="nameInstend">当枚举没有定义DescriptionAttribute,是否用枚举名代替,默认使用</param>
 6         /// <returns>枚举的Description</returns>
 7         public static string GetDescription(this Enum value, bool nameInstend = true)
 8         {
 9             Type type = value.GetType();
10             string name = Enum.GetName(type, value);
11             if (name==null)
12             {
13                 return null;
14             }
15             FieldInfo field = type.GetField(name);
16             DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
17             if (attribute==null&&nameInstend==true)
18             {
19                 return name;
20             }
21             return attribute==null? null :attribute.Description;
22         }
View Code

相关文章: