之前记录过一种获取枚举描述信息的方法:http://cat.xiexiao.com/enum_description/

今天,发现扩展一下Enum的方法更好,不过就是只能C#3.0才可以使用扩展方法。

1。定义enum
using System;
using System.ComponentModel;

  public enum TimeOfDay
        {
            [Description("上午")]
            Moning = 0,
            [Description("中午")]
            Afternoon = 1,
            [Description("晚上")]
            Evening = 2,
        };

2.定义扩展:

        /// <summary>
        /// 获取描述信息
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static string description(this 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();
        }

这样子就可以直接用方法:.description()来获取描述信息了。没有描述信息,返回en.ToString()。

这里可以搞到wave邀请

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-03-07
  • 2022-12-23
  • 2022-02-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案