不知不覺在公司一個多月了,這一個月做了一個支票申請的web頁面功能,都不是特別難,審核有公司給的工作流,分頁工具和很多公用工具公司也都給了,所以覺得難度都不是很大。今天主管讓我們修改了以前做的項目的代碼規范,有一個問題是html的select標簽綁定數據問題,不能用之前寫死的,而是要求根據枚舉然后動態給select綁定數據,這是我在公司帶的遇到的第二個大問題了。
枚舉的基礎知識網上都有,就不說了,我想說一下枚舉除了名稱和值以外還一個特性,那就是描述,而一般值是int,名稱是英文,描述可以是中文作為select的option顯示,定義如下:
public enum Url{ [Description("http://www.thylx.net")] 個人博客 = 1, [Description("http://blog.163.com/thylx133@126/")] 網易博客 = 2, [Description("http://www.8eshare.com/")] 八邑分享 = 3 }
然后就是獲取C#枚舉中的描述值的方法了:
/// <summary> /// 獲取描述信息 /// </summary> /// <param name="en">枚舉</param> /// <returns></returns> public static string GetEnumDes(Enum en) { Type type = en.GetType(); MemberInfo[] memInfo = type.GetMember(en.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) return ((DescriptionAttribute)attrs[0]).Description; } return en.ToString(); }
這些都是從網上po來的,謝謝那位大神,這個寫得很清楚了,然后再附上一些enum轉int,int轉enum,string轉enum的方法:
Colors color = (Colors)2 int-》enum(個人覺得這個方法很好用)
(int)Colors.Red enum-》int
(Colors)Enum.Parse(typeof(Colors), "Red") string-》enum
Enum.GetName(typeof(Colors),3)) enum-》string
還有一些enum常用的方法,GetValues和GetName(這個可以查看msdn幫助文檔)。