枚举的创建和描述文本的获取

1.添加引用System.ComponentModel.Composition.dll

2.创建枚举,如下

namespace MysteelDataWeb.Enums
{
    public enum Frequency
    {
        [Description("日")]
        Day = 0,
        [Description("周")]
        Week = 1,
        [Description("旬")]
        Xun = 2,
        [Description("月")]
        Month = 3,
        [Description("季")]
        Season = 4,
        [Description("年")]
        Year = 5
    }
}

3.获取描述的文本内容

 public class EnumHelper
    {
        public static string GetEnumDescription(Enum value)
        {
            FieldInfo enumInfo = value.GetType().GetField(value.ToString());

            if (enumInfo == null)
                return string.Empty;


            DescriptionAttribute[] enumAttributes = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (enumAttributes.Length > 0)
            {
                return enumAttributes[0].Description;
            }
            return value.ToString();
        }


        public static Dictionary<string, string> GetAllEnumDescription(Type enumType)
        {
            var dicList = new Dictionary<string, string>();

            if (enumType.IsEnum)
            {
                foreach (var item in Enum.GetValues(enumType))
                {
                    dicList.Add(((int)item).ToString(), GetEnumDescription((Enum)item));
                }
            }

            return dicList;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值