C# 反射获取Description特性值和属性名

发布时间 2023-06-09 18:12:33作者: Misterj
 public static Dictionary<string, string> GetAttributes<T>()
 {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string condition = "查询条件:" + "\r\n";
            Type type = typeof(T);//model.GetType()
            T t = (T)Activator.CreateInstance(type);
            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            if (properties.Length <= 0)
            {
                return dic;
            }
            foreach (PropertyInfo property in properties)
            {
                if (property.PropertyType.IsValueType || property.PropertyType.Name.StartsWith("String"))
                {              
                    object[] objs = property.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);

                    if (objs.Length > 0 && ((DescriptionAttribute)objs[0]).Description != null)
                    {
                        string description = ((DescriptionAttribute)objs[0]).Description;
                        dic.Add(description, property.Name);
                    }
                }
            }
            return dic;
}