1.應用的命名空間
using System.ComponentModel;
using System.Reflection;
2、定義枚舉類
枚舉類
1 public enum BagType 2 { 3 [Description("書包1")] 4 schoolbag1, 5 6 [Description("書包2")] 7 schoolbag2, 8 9 [Description("書包3")] 10 schoolbag3 11 }
3、獲取枚舉類所有屬性的描述信息
獲取描述信息方法
1 public void GetEnumDesc<Ttype>(Ttype Enumtype) 2 { 3 if (Enumtype == null) throw new ArgumentNullException("Enumtype"); 4 if (!Enumtype.GetType().IsEnum) throw new Exception("參數類型不正確"); 5 6 FieldInfo[] fieldinfo = Enumtype.GetType().GetFields(); 7 foreach (FieldInfo item in fieldinfo) 8 { 9 Object[] obj = item.GetCustomAttributes(typeof(DescriptionAttribute), false); 10 if (obj != null&&obj.Length!=0) 11 { 12 DescriptionAttribute des = (DescriptionAttribute)obj[0]; 13 Console.WriteLine(des.Description); 14 } 15 } 16 }
4、知識總結:
4.1熟悉FieldInfo的用法和屬性(發現字段特性並提供對字段員數據的訪問權)
4.2理解C#泛型的應用
這個方法如果大家在項目當中擴展的好可以起到一定的舉足輕重的作用。如果有什么建議的同仁;希望多多指點;感激不盡;您的指點讓我又進步了一點。
