Exemplo n.º 1
0
        /// <summary>
        /// 枚举返回成数据表
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static DataTable GetEnumTable(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException();
            }

            DataTable dt = new DataTable();

            dt.Columns.Add("Text", typeof(System.String));
            dt.Columns.Add("Value", typeof(System.String));

            Type typeDescription = typeof(TextAttribute);

            FieldInfo[] fields = enumType.GetFields();

            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum == true)
                {
                    DataRow dr = dt.NewRow();

                    dr["Value"] = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();

                    object[] arr = field.GetCustomAttributes(typeDescription, true);
                    if (arr.Length > 0)
                    {
                        TextAttribute aa = (TextAttribute)arr[0];
                        dr["Text"] = aa.Text;
                    }
                    else
                    {
                        dr["Text"] = field.Name;
                    }
                    dt.Rows.Add(dr);
                }
            }
            return(dt);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 获取枚举的列表
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <returns>枚举的键值集合</returns>
        public static List <EnumEntity> GetEnumList(Type enumType)
        {
            if (!enumType.IsEnum)
            {
                throw new InvalidOperationException();
            }

            List <EnumEntity> entitys = new List <EnumEntity>();

            Type typeDescription = typeof(TextAttribute);

            FieldInfo[] fields = enumType.GetFields();

            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum == true)
                {
                    EnumEntity entity = new EnumEntity();

                    entity.Value = (int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null);

                    object[] arr = field.GetCustomAttributes(typeDescription, true);
                    if (arr.Length > 0)
                    {
                        TextAttribute aa = (TextAttribute)arr[0];
                        entity.Text = aa.Text;
                    }
                    else
                    {
                        entity.Text = field.Name;
                    }
                    entitys.Add(entity);;
                }
            }

            return(entitys);
        }