码迷,mamicode.com
首页 > 其他好文 > 详细

Description相关

时间:2021-03-18 14:08:16      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:bool   attr   field   desc   custom   static   value   att   property   

 public static class DescriptionUtil
    {
        /// <summary>
        /// 获得枚举的Description
        /// </summary>
        /// <param name="value">枚举值</param>
        /// <param name="nameInstead">当枚举值没有定义DescriptionAttribute,是否使用枚举名代替,默认是使用</param>
        /// <returns>枚举的Description</returns>
        public static string GetDescription(this System.Enum value, Boolean nameInstead = true)
        {
            Type type = value.GetType();
            string name = System.Enum.GetName(type, value);
            if (name == null)
            {
                return null;
            }

            FieldInfo field = type.GetField(name);
            DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

            if (attribute == null && nameInstead == true)
            {
                return name;
            }
            return attribute?.Description;
        }


        public static string GetDescription(this object obj)
        {
            foreach (object attr in obj.GetType().GetCustomAttributes(false))
            {
                if (attr is DescriptionAttribute)
                    return (attr as DescriptionAttribute).Description;
            }

            return "";
        }

        public static string GetDescription<T>(this object obj, Expression<Func<T, string>> expr)
        {
            PropertyDescriptor pd = TypeDescriptor.GetProperties(typeof(T))[GetPropertyName(expr)];
            DescriptionAttribute description = pd == null ? null : pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
            return description == null ? "" : description.Description;
        }

        public static string GetPropertyName<T>(Expression<Func<T, string>> expr)
        {
            var name = ((MemberExpression)expr.Body).Member.Name;
            return name;
        }
    }

Description相关

标签:bool   attr   field   desc   custom   static   value   att   property   

原文地址:https://www.cnblogs.com/ives/p/14548939.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!