13 /// 获取枚举变量值的 Description 属性 14 /// 15 ///
枚举变量 16 ///
如果包含 Description 属性,则返回 Description 属性的值,否则返回枚举变量值的名称
17 public static string GetDescription(this object obj) 18 { 19 return GetDescription(obj, false); 20 } 21 22 ///
23 /// 获取枚举变量值的 Description 属性 24 /// 25 ///
枚举变量 26 ///
是否改变为返回该类、枚举类型的头 Description 属性,而不是当前的属性或枚举变量值的 Description 属性 27 ///
如果包含 Description 属性,则返回 Description 属性的值,否则返回枚举变量值的名称
28 public static string GetDescription(this object obj, bool isTop) 29 { 30 if (obj == null) 31 { 32 return string.Empty; 33 } 34 try 35 { 36 Type _enumType = obj.GetType(); 37 DescriptionAttribute dna = null; 38 if (isTop) 39 { 40 dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType, typeof(DescriptionAttribute)); 41 } 42 else 43 { 44 FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj)); 45 dna = (DescriptionAttribute)Attribute.GetCustomAttribute( 46 fi, typeof(DescriptionAttribute)); 47 } 48 if (dna != null && string.IsNullOrEmpty(dna.Description) == false) 49 return dna.Description; 50 } 51 catch 52 { 53 } 54 return obj.ToString(); 55 } 56 } 57 } 使用方法很简单: 01 using System; 02 using System.Collections.Generic; 03 using System.Linq; 04 using System.Windows.Forms; 05 using System.ComponentModel; 06 using com.hetaoos.Utils.Extensions;//这一句是必须的,否则无法使用扩展方法 07 using System.Diagnostics; 08 09 namespace com.hetaoos 10 { 11 static class Program 12 { 13 ///
14 /// 应用程序的主入口点。 15 /// 16 [STAThread] 17 static void Main() 18 { 19 ProcessedDataResultType resultType = ProcessedDataResultType.BkgrdMap; 20 ProcessedDataWaringResult ret = new ProcessedDataWaringResult() { ResultType = ProcessedDataResultType.WaringResult }; 21 Debug.Print("枚举类型的描述属性:{0}", resultType.GetDescription(true)); 22 Debug.Print("单个枚举变量的描述属性:{0} --> {1}", resultType, resultType.GetDescription()); 23 Debug.Print("类类型的描述属性:{0}", ret.GetDescription(true)); 24 Debug.Print("类类型的属性的描述属性:{0} --> {1} --> {2}", ret.ResultType, ret.ResultType.GetDescription(), ret.ResultType.GetDescription(true)); 25 } 26 27 ///
28 /// 处理结果类型 29 ///