枚舉擴展方法獲取枚舉Description


枚舉擴展方法
 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”

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM