有時候咱們用數字來區分一些類型,如1:中國銀行,2:建設銀行,3:工商銀行,……。
這時候我在代碼中一般會定義枚舉來與定義的一一對應,並在該枚舉值上設置特性來表示所表明的含義,這樣避免多處寫一些數字來標識所表明的類型。並且後續添加修改也很方便。
首先,自定義一個特性描述類:
1 public class DescriptionAttribute : Attribute 2 { 3 public static readonly DescriptionAttribute Default; 4 5 public DescriptionAttribute(); 6 public DescriptionAttribute(string description); 7 8 public virtual string Description { get; } 9 protected string DescriptionValue { get; set; } 10 11 public override bool Equals(object obj); 12 public override int GetHashCode(); 13 }
定義枚舉:
1 public enum EnumType 2 { 3 [Description("第一")] 4 FIRST, 5 [Description("第二")] 6 SECOND, 7 [Description("第三")] 8 THIRD, 9 }
將枚舉特性值轉爲註釋信息:
1 /// <summary> 2 /// 將枚舉特性值轉爲註釋信息 3 /// </summary> 4 /// <param name="enumType"></param> 5 /// <returns></returns> 6 public static string ToString<T>(this T enumType) 7 { 8 Type type = enumType.GetType(); 9 FieldInfo fd = type.GetField(enumType.ToString()); 10 if (fd == null) 11 return string.Empty; 12 var attributes = fd.GetCustomAttributes(typeof(DescriptionAttribute), false); 13 14 var txt = string.Empty; 15 foreach (DescriptionAttribute attr in attributes) 16 { 17 txt = attr.Description; 18 break; 19 } 20 return txt; 21 }
調用:ide
1 var name = EnumType.FIRST.ToString<EnumType>();2 //第一