对象反射

来源:互联网 发布:淘宝店香港男装品牌 编辑:程序博客网 时间:2024/05/11 20:07
 /// <summary>
        ///  查询数据将数据绑定到repter控件上展示
        /// </summary>
        /// <typeparam name="T">传入对象类型</typeparam>
        /// <param name="pageIndex">分页的页数</param>
        /// <param name="count">每页显示的条数</param>
        /// <param name="data">查询条数</param>
        /// <param name="str">lbl控件上显示的文本</param>
        /// <param name="commonType">传入对象</param>
        private void ShowData<T>(int pageIndex, long count, TestData data, string str, CommonType commonType)
        {
            List<object> commonTypes = commonType.GetList(data, pageIndex, PagerBar.PageSize, out count);
            if (commonTypes != null && commonTypes.Count > 0)
            {
                foreach (Object entity in commonTypes)
                {
                    Type type = entity.GetType(); //反射对象类型
                    PropertyInfo[] propertys = type.GetProperties(); //反射对象属性的集合
                    foreach (PropertyInfo p in propertys)
                    {
                        if (p.Name == "NewTime")//判断属性是不是创建时间
                        {
                            try
                            {
                                //根据条件获取属性中的值
                                //IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == "NewTime" select pi;
                                PropertyInfo property = type.GetProperty("NewTime");
                                Object value = property.GetValue(entity, null);
                                p.SetValue(entity, (DateTime)value, null); //给属性对象设置值
                            }
                            catch (TargetException)
                            {
                                p.SetValue(entity, null, null);
                            }
                        }
                    }
                }
                Suppliers.DataSource = commonTypes;
                Suppliers.DataBind();
            }
            lbtable.Text = str;
        }