zoukankan      html  css  js  c++  java
  • Description相关

     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;
            }
        }
    
    留待后查,同时方便他人
    联系我:renhanlinbsl@163.com
  • 相关阅读:
    python拆包与装包-*args,**kwargs
    mybatis学习4-CRUD操作
    mybatis学习3-入门案例,注解方式
    mybatis学习1-前置,复习Jdbc
    spring框架学习-aop
    spring学习1-第一个spring项目
    spring概述
    idea的一些个人设置
    maven的一些个人设置
    VBA文件对话框的应用(VBA打开文件、VBA选择文件、VBA选择文件夹,VBA遍历文件夹)
  • 原文地址:https://www.cnblogs.com/ives/p/14548939.html
Copyright © 2011-2022 走看看