C# 读取枚举描述信息实例

时间:2023-04-25 12:00:56

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Data;
using System.ComponentModel;
using System.Web.UI.WebControls;

namespace SieCom.YQ.Common
{
    public class CommondLibray
    {
        public CommondLibray()
        {
            //TODO
        }

#region 根据枚举值获取枚举描述信息(单个)
        /// <summary>
        /// 根据枚举值获取枚举描述信息(单个)
        /// </summary>
        /// <typeparam name="TEnum">枚举</typeparam>
        /// <param name="value">枚举值</param>
        /// <returns></returns>
        public static string GetEnumDescription<TEnum>(object value)
        {
            string result = string.Empty;
            Type enumType = typeof(TEnum);
            if (enumType.IsEnum)
            {
                var name = System.Enum.GetName(enumType, Convert.ToInt32(value));
                if (name != null)
                {
                    object[] objs = enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (objs != null && objs.Length > 0)
                    {
                        DescriptionAttribute attr = objs[0] as DescriptionAttribute;
                        result = attr.Description;
                    }
                    else
                    {
                        //TODO
                    }
                }
                else
                {
                    //TODO
                }
            }
            return result;
        }
        #endregion

#region 获取枚举列表
        /// <summary>
        /// 获取枚举列表
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <param name="IsAll">是否在枚举列表前加入全部</param>
        /// <returns>枚举对应的ListItem</returns>
        public static List<ListItem> GetEnumList(Type enumType, bool IsAll)
        {
            List<ListItem> list = new List<ListItem>();
            if (enumType.IsEnum)
            {
                if (IsAll)
                    list.Add(new ListItem("--请选择--", "-1"));
                Type type = typeof(DescriptionAttribute);
                System.Reflection.FieldInfo[] files = enumType.GetFields();
                string strText = string.Empty;
                string strValue = string.Empty;
                foreach (System.Reflection.FieldInfo field in files)
                {
                    if (field.IsSpecialName) continue;
                    strValue = field.GetRawConstantValue().ToString();
                    object[] arr = field.GetCustomAttributes(type, true);
                    if (arr.Length > 0)
                        strText = (arr[0] as DescriptionAttribute).Description;
                    else strText = field.Name;

list.Add(new ListItem(strText, strValue));
                }
            }
            return list;
        }
        #endregion
    }
}