返回自定义类的所有属性名

发布时间 2023-11-28 16:47:30作者: 剑小秀
        /// <summary>
        /// 返回类型的所有属性名
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static Dictionary<string, Type> GetPropertyInfoArray<T>()
        {
            Dictionary<string, Type> propNameAndType = new Dictionary<string, Type>();

            List<string> propNames = new List<string>();
            PropertyInfo[] props = null;
            Type t = typeof(T);//获得该类的Type
            object obj = Activator.CreateInstance(t);
            props = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            if (props != null)
            {
                for (int i = 0; i < props.Length; i++)
                {
                    propNameAndType.Add(props[i].Name, props[i].PropertyType);
                }
            }
            return propNameAndType;
        }