获取枚举描述

    /// <summary>
    /// 枚举测试
    /// </summary>
    public enum TestTypeEnum
    {

        [Description("书籍")]Book = 1,

        [Description("手机")]Phone = 2
    }
    public static class EnumHelp
    {
        public static string GetDescription(this Enum value)
        {
            Type enumType = value.GetType();
            string name = Enum.GetName(enumType, value);
            if (name != null)
            {
                FieldInfo fieldInfo = enumType.GetField(name);
                if (fieldInfo != null)
                {
                    if (Attribute.GetCustomAttribute(fieldInfo,
                        typeof(DescriptionAttribute), false) is DescriptionAttribute attr)
                    {
                        return attr.Description;
                    }
                }
            }
            return null;
        }
    }
var dec = TestTypeEnum.Book.GetDescription();

 

posted @ 2019-06-21 18:01  向萧  阅读(117)  评论(0编辑  收藏  举报