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

 public static Dictionary<string, string> GetAttributes<T>()
 {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            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;
}

 

posted @ 2023-06-09 18:09  Misterj  阅读(521)  评论(0编辑  收藏  举报