码迷,mamicode.com
首页 > 其他好文 > 详细

枚举扩展方法获取枚举Description

时间:2016-10-28 02:14:57      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:ted   art   alt   contract   ini   one   images   public   hid   

枚举扩展方法
技术分享
 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

枚举类

技术分享
 1  public enum WeekDay
 2     {
 3         [Description("星期一")]
 4         one=1,
 5         [Description("星期二")]
 6         two =2,
 7         three=3,
 8         four=4,
 9         five=5,
10         six=6,
11         seven=7
12 
13     }
View Code

测试

           //枚举测试
            WeekDay w1 = WeekDay.one;
            string strw1 = w1.GetDescription();// strw1= “星期一”

            WeekDay w3 = WeekDay.three;
            string strw2 = w3.GetDescription();// strw3=“three”

 

枚举扩展方法获取枚举Description

标签:ted   art   alt   contract   ini   one   images   public   hid   

原文地址:http://www.cnblogs.com/bindot/p/kuozhanfangfa.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!