1. 程式人生 > >Enum新增說明並將說明和int值放在集合中並選定當前項

Enum新增說明並將說明和int值放在集合中並選定當前項

實現: 

 public static class EnumExtension
    {
        /// <summary>
        /// 獲取列舉的描述,需要DescriptionAttribute屬性
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetDescription(this Enum e)
        {
            //獲取列舉的Type型別物件
            var type = e.GetType();
            //獲取列舉的所有欄位
            var fields = type.GetFields();

            //遍歷所有列舉的所有欄位
            foreach (var field in fields)
            {
                if (field.Name != e.ToString())
                {
                    continue;
                }
                //第二個引數true表示查詢EnumDisplayNameAttribute的繼承鏈

                if (field.IsDefined(typeof(DescriptionAttribute), true))
                {
                    var attr = field.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }

            //如果沒有找到自定義屬性,直接返回屬性項的名稱
            return e.ToString();
        }

        /// <summary>
        /// 根據列舉獲取下拉框列表
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static List<KeyValue> GetSelectList(this Enum en)
        {
            var list = new List<KeyValue>();
            foreach (var e in Enum.GetValues(en.GetType()))
            {
                list.Add(new KeyValue() { Value = GetDescription(e as Enum), Key = ((int)e).ToString(), IsSelected = e.ToString() == en.ToString() });
            }
            return list;
        }
        
    }
    public class KeyValue {
        public string Key { get; set; }
        public string Value { get; set; }
        public bool IsSelected { get; set; }
    }

呼叫:

 class Program
    {
        static void Main(string[] args)
        {
            var list = OrderState.NoPay.GetSelectList();
            foreach (var item in list)
            {
                string str = string.Format("Key:{0},Value:{1},Selected:{2}", item.Key, item.Value, item.IsSelected);
                Console.WriteLine(str);
            }
            Console.ReadKey();
        }
    }
    public enum OrderState
    {
        [Description("未付款")]
        NoPay = 0,
        [Description("支付成功")]
        PaySuccess = 1,
        [Description("支付失敗")]
        PayError = 2,
        [Description("已退款")]
        PayReturn = 3
    }

結果: