程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 枚舉的使用總結,枚舉使用總結

枚舉的使用總結,枚舉使用總結

編輯:關於.NET

枚舉的使用總結,枚舉使用總結


C#中枚舉的使用

1.原則上全部使用枚舉,不使用常量,除非常量是一個,不是一組

2.如果一組常量中增減常量後要對代碼修改,則要將這組常量定義為枚舉

3.如果一組常量中增減常量後代碼不需要修改,則要將這組常量存儲到字碼主檔中,由數據庫進行維護

枚舉擴展方法

1.將字符串轉為枚舉

        /// <summary>
        /// 通枚舉項的名字轉換為枚舉
        /// </summary>
        /// <typeparam name="TEnum">要轉換的枚舉類型</typeparam>
        /// <param name="enumName">枚舉項的名字</param>
        /// <returns></returns>
        public static TEnum ToEnum<TEnum>(this string enumName) where TEnum : struct, IComparable, IFormattable, IConvertible
        {
           return (TEnum)Enum.Parse(typeof(TEnum), enumName);
        }

 

2.獲取枚舉的描述,在枚舉項定義時加上Description 特性

        /// <summary>
        /// 獲取一個枚舉值的描述
        /// </summary>
        /// <param name="obj">枚舉值</param>
        /// <returns></returns>
        public static string GetDescription(this Enum obj)
        {
            FieldInfo fi = obj.GetType().GetField(obj.ToString());
            DescriptionAttribute[] arrDesc = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return arrDesc[0].Description;
        }

 

3.獲取枚舉的數據清單,方便綁定到下拉列表等控件

        /// <summary>
        /// 獲取枚舉的(描述,名稱,值)數據列表,通常用於綁定到控件
        /// </summary>
        /// <typeparam name="TEnum">枚舉類型</typeparam>
        /// <returns></returns>
        public static List<Tuple<string, string, int>> GetEnumDataList<TEnum>() where TEnum : struct  , IComparable, IFormattable, IConvertible
        {
            List<Tuple<string, string, int>> dataList = new List<Tuple<string, string, int>>();
            Type t = typeof(TEnum);
            if (!t.IsEnum)
            {
                return null;
            }
            Array arrays = Enum.GetValues(t);
            for (int i = 0; i < arrays.LongLength; i++)
            {
                Enum tmp = (Enum)arrays.GetValue(i);
                string description = GetDescription(tmp);
                string name = tmp.ToString();
                int value = Convert.ToInt32( tmp);
                dataList.Add(new Tuple<string, string, int>(description, name, value));
            }
            return dataList;
        }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved