.Net Attribute詳解(下) - 使用Attribute武裝枚舉類型
接上文.Net Attribute詳解(上)-Attribute本質以及一個簡單示例,這篇文章介紹一個非常實用的例子,相信你一定能夠用到你正在開發的項目中。枚舉類型被常常用到項目中,如果要使用枚舉ToString方法直接輸出字符串, 常常不是我們想要的輸出,因為它是安裝定義的名稱輸出字符串。比如你有一個性別枚舉,有Man, Woman. 你在中文系統中,在創建用戶的頁面上,這個枚舉代表的下拉框,當然不是顯示Man和Woman的,而是要顯示”男”和”女“。 下面就介紹如何使用Attribute非常方便的輸出我們想要的字符串。
1, 使用System.ComponentModel.DescriptionAttribute
比如,下面這個枚舉
enum Gender { Man, Woman };
在使用上DescriptionAttribute後,可以改造成這樣
enum Gender { [Description(“男”)] Man, [Description(“女”)] Woman };
好了,使用Attribute的三個步驟:
Attribute的定義, Attribute的使用(貼標簽), Attribute的讀取和使用(根據標簽做不同處理)
第一步,我們使用了系統中的Attribute,貼標簽已經做好了,接下來時對於Attribute的讀取和使用了。
2, EnumHelper類
下面定義的EnumHelper類,使用擴展方法,為枚舉提供了非常方便的方式輸出Description. 比如,我們可以這樣使用下面的方法,來得到對應項的字符串:
Gender.Man.GetDescription()
上面輸出的就會我們想要的”男”, 而不是”Man”.
/// <summary> /// Contains methods for working with <see cref="Enum"/>. /// </summary> public static class EnumHelper { /// <summary> /// Gets the specified enum value‘s description. /// </summary> /// <param name="value">The enum value.</param> /// <returns>The description or <c>null</c> /// if enum value doesn‘t have <see cref="DescriptionAttribute"/>.</returns> public static string GetDescription(this Enum value) { var fieldInfo = value.GetType().GetField(value.ToString()); var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes( typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : null; } /// <summary> /// Gets the enum value by description. /// </summary> /// <typeparam name="EnumType">The enum type.</typeparam> /// <param name="description">The description.</param> /// <returns>The enum value.</returns> public static EnumType GetValueByDescription<EnumType>(string description) { var type = typeof(EnumType); if (!type.IsEnum) throw new ArgumentException("This method is destinated for enum types only."); foreach (var enumName in Enum.GetNames(type)) { var enumValue = Enum.Parse(type, enumName); if (description == ((Enum)enumValue).GetDescription()) return (EnumType)enumValue; } throw new ArgumentException("There is no value with this description among specified enum type values."); } }
3. Attribute在MVC中的Razor view engine 中的使用
在Model上我們可以添加上DisplayAttribute, 比如
public class User { [Display(Name = "User Name)] public string Name{get;set;} }
這樣在view中使用Html.DisplayFor(), 輸出的就是User Name。
這裏的使用和我們上面的EnumHelper的原理完全相同。
還有關於Model上的驗證相關的Attribute, 比如MaxLength.
[MaxLength(100, ErrorMessage = "The max length is 100")] public string Name{get;set;}
把MaxLength加在Name上,它不僅能夠作為MVC中的驗證,而且會在Entity Framwork中,作為數據檢查規則。因為這個屬性披上了一個外衣,上面寫著“我的最大長度是100”,如果有任何數據有效性檢查的類,都會看到這個外衣,同時檢查這個屬性的長度是否符合要求。
總之,理解了什麽是Attribute, 以及原理,對於理解.net中無處不在的,那些加載類上或者屬性上的[]東東,一定能夠更加容易。
.Net Attribute詳解(下) - 使用Attribute武裝枚舉類型